private copy of the pointer

In below example, we pass character array to strlen. Now what is actually passed is a reference to the first element of the array, and so we use a pointer in our argument list to point to that first position.

1
2
3
4
5
6
7
8
9
10
11
int strlen(char *s)
{
    int n;
    for (n = 0; *s != '\0', s++)
        n++;
    return n;
}

strlen("hello, world");	/* string constant */
strlen(array);		/* char array[100]; */
strlen(ptr);		/* char *ptr; */


The book says:

"s++ has no effect on the character string in the function that called strlen, but merely increments strlen's private copy of the pointer."

Private copy of the pointer? What does that mean? I thought a pointer is memory that points to another piece of memory, and in this case, it is pointing to the first element of char array. This isn't a copy of a pointer, is it?
The book seems to have worded it poorly. What it means is that if you have:

1
2
3
char buffer[] = "abcd";
char *firstPointer = buffer;
char *secondPoitner = buffer;


At that point, both pointers point to the first element.

secondPointer++;

Now the second pointer points to the next element, but the first pointer points to the first element. Basically, the pointer is copied in to the function when you call it, so you have a second copy of it. You can alter the new copy of the pointer without changing the old copy of it.
"You can alter the new copy of the pointer without changing the old copy of it. "

And what if you want to alter the original copy of the pointer from the calling function? Isn't that the whole point of using pointers in function arguments - to modify the original, rather than working with copy
Isn't that the whole point of using pointers in function arguments - to modify the original, rather than working with copy

The "whole point" of using pointers is to pass an address so that the function may work on whatever is at the address passed. It is not so the function may modify the address. If we want to modify a pointer, we pass a pointer to a pointer to whatever type we are ultimately dealing with.
Topic archived. No new replies allowed.