Reputation: 23
In the classic swap function, when we pass in two pointers, the values the pointers point to will swap. However in this simple function
int leng (char *a)
{
int n;
for (n=0; *a!='\0'; a++)
n++;
return n;
}
After the function is called, the pointer still points to the first element of the array instead of the last element. Why is that? How is it different from the swap function?
Upvotes: 2
Views: 175
Reputation: 12169
You are passing in a pointer by value. The pointer value is copied on to the stack during the function call. You are incrementing that stack variable, which then goes away when the function returns.
Upvotes: 2
Reputation: 10487
You probably want a pointer-to-a-pointer, not just a regular pointer. (Pointers themselves are passed by value, you're changing the value of the copy of the pointer passed in).
Upvotes: 1
Reputation: 183321
It's actually the same as the swap
function: the swap
function lets you change the values that are pointed-to, but it doesn't let you change the pointers themselves. Likewise, leng
can change the characters in the string that a
points to, but changes to a
itself — changing it to point to a different array element — will not be seen by the caller.
If you wanted to change that, you could do so by writing:
int leng (char **a)
{
int n;
for (n=0; **a!='\0'; *a++)
n++;
return n;
}
and pass in a pointer to a
.
Upvotes: 1
Reputation: 8049
A pointer is itself an object. In this case, you are passing the pointer by value, not by reference, so any changes to the pointer itself will not be reflected outside the function. If you were to change the object the pointer points to in the function, those changes would persist outside the function.
Try:
int leng (char** a)
{
int n;
for (n=0; **a!='\0'; (*a)++)
n++;
return n;
}
leng(&pointer);
Upvotes: 6