If I\'ve declared a pointer p
as int *p
; in main module, I can change the address contained by p
by assigning p=&a;
w
For a primitive data type such as an int
, the double pointers are not necessary. You can write directly into the address where the int
is stored, treating its address as a pointer in the function being called. This is unlike a char
array ("string") where the size of what is pointed to is variable and you must therefore use another level of indirection when changing it from within a called function. Try this:
void foo(int *oldVal)
{
int newVal = 99; // or whatever you want
*oldVal = newVal;
}
int main(int argc, char *argv[])
{
int someVal = 0;
foo(&someVal); // we send its address to foo()
printf("someVal is now %d.\n", someVal);
return EXIT_SUCCESS;
}