Reputation: 633
There are some things that I still don't really understand with pointers when you pass them into functions. If declare a function like
void help (const int *p)
can I modify the argument p
within the function help
?
Can I change what the pointer is pointing too?
Thanks for the clarification.
Upvotes: 0
Views: 118
Reputation: 1572
The easiest way to understand const notation in C is to say the declaration out loud. Start with the name and go left:
const int *p; // 'p' is a pointer to an int that is const
This is by the way equal to:
int const *p;
This suggests that you can change the what p points at, but you can't change whatever it points at. So you have read-only access. However if you'd have something like this:
int * const p; // 'p' is a const pointer to an int
...then you could change the memory pointed to by p as much as you want, but you couldn't change p
.
Upvotes: 1
Reputation: 14458
In this case, since p
is declared as a const int *
, an attempt to modify p
will be disallowed by the compiler.
However, if p
were a plain old int *
, you could modify the thing that p
is pointing to, and the caller would notice. Say you wrote:
void foo(void) {
int n = 100;
help1(&n);
printf("n = %d", n);
n = 100;
help2(&n);
printf("n = %d", n);
}
void help1(int *p) {
*p = 50;
}
void help2(int *p) {
p = (int *)malloc(sizeof(int));
*p = 50;
free(p);
}
Then calling foo()
would cause your program to print
n = 50
n = 100
In this program, help1
changes the thing that p
points to, and the caller can see it. On the other hand, help2
makes p
point to a different place in memory, and anything help2
does to modify that other location in memory is not visible to the caller.
Upvotes: 1
Reputation: 224844
Yes, you can modify p
. However, it won't change in the caller. C is a pass-by-value language. Check out the C FAQ, which has a question about exactly this situation.
Upvotes: 4