copying pointers

When I have a char pointer and it's initialized to a memory position, like this:
1
2
char *p
p = alloc(len
)

where alloc is just some buffer memory:

1
2
3
4
5
6
7
8
char *alloc(int n)
{
    if (allocbuf + ALLOCSIZE - allocp >= n) {
        allocp += n;
        return allocp - n; /* old p */
    } else	
        return 0;
}


When I pass the pointer p to a function, which makes a copy of the pointer and then does pointer arithmetic to increment it:

1
2
3
4
5
strcpy(p, line);
void strcpy(char *s, char *t) { 
    while (*s++ = *t++) 
        ; 
}


Now the strcpy function is incrementing the copy, not the original. So when we return control back to the function call, is p pointer still pointing at the same address as it was prior to the function call? Or is it now pointing to the same address that it's copy is pointing at in the strcpy function?
p is indeed still pointing to the same address that it was before.

Also, that strcpy function doesn't look safe.
Aish, I spent too much time in Java-land and I forgot about null termination of strings. Oops.

-Albatross
Last edited on
The strcpy is fine, but why not make a standard one with a few tweaks.
1
2
3
4
5
6
char* strcpy(char* s, const char* t) { 
    char* tmp = s;
    while (*s++ = *t++) 
        ;
    return tmp;
}


That example is presented in James Coplien's C++ book as obvious. It gave me a double take.

It works because of the use of the post increment. The assignment is done before the test for null.
Last edited on
Topic archived. No new replies allowed.