views:

144

answers:

2

I want to take a substring of the string buffer by doing something like the below. I don't know if it's possible (I've been coding in C for all of about 6 hrs now, but feel free to be as technical as you like, I think I can handle it (though I may be wrong))

Edit: I want to take a substring of buffer from the beginning of buffer to the first space.

if (buffer[c] == ' ') {
    in_addr_t addr;
    char *ptr = *buffer;
    if(inet_aton("*ptr to *ptr+c", &addr)!=0){
           //do stuff;
    }
}
+4  A: 

I have to make one assumption since there are a number of problems with the code: Assuming that buffer[c] is the first character before the inet address

if (buffer[c] == ' ')
{
     in_addr_t addr
     if (inet_aton(&buffer[c+1], &addr))
          // do stuff
}

Note:

  • inet_aton is deprecated since it does not support ipv6. Use int inet_pton(int af, const char *src, void *dst); for forward compatibility.

-- Edit --
To take the substring from the beginning of buffer to (but not including) buffer[c], any of these will work:

1

char buf2 [MAX];
strncpy (buf2, buffer, c);
buf2 [c] = '\000';

2

char buf2 [MAX];
sprintf (buf2, "%.*s", c, buffer);

3

char buf2 [MAX];
int  j;
for (j = 0;  j < c;  ++j)
    buf2 [j] = buffer [j];
buf2 [c] = '\000';
wallyk
piggles
Carl Norum
wallyk
thanks a lot. I got it working and it feels beautiful. The only thing that pains me is that I had to artificially (using a break) exit my for loop.
piggles
+2  A: 

If you can modify the original buffer, you could just ignore your ptr variable and do:

if (buffer[c] == ' ') {
    in_addr_t addr;
    buffer[c] = '\0';
    if (inet_aton(buffer, &addr) != 0) {
        // do stuff;
    }
}

If you can't modify the original buffer, just use strncpy() to copy the part you care about out into a new buffer.

Carl Norum
can I then move the pointer to buffer to the beginning of the new string? like *buffer = *buffer+c or something like that?
piggles
Close; to do that you want `buffer += c + 1`. The `+1` gets your pointer past the `\0` and to the beginning of the new string. Be careful that you keep track of the original pointer if it matters (because you might need to `free()` it for example.)
Carl Norum
and keeping track of the old pointer would just be char temp = buffer?
piggles
As an aside, your comment here and the original question seem to show a bit of overuse of the `*` operator; make sure you are understanding the difference between operations on the objects pointed to and operations on the pointers themselves.
Carl Norum
@Mechko, almost. `char *temp = buffer`. You need a pointer type to save a copy of a pointer.
Carl Norum
Thank you very much, too.
piggles