+ 1
In functions involving pointers, is the pointer local to function or global?
Functions involving Pointers
3 odpowiedzi
+ 3
The whole point of pointers (lol) is that they make this possible!
Without a pointer, you are handing a *copy* of the value to the function. So if it messes with the copy, the original isn't effected.
A pointer is something different: Imagine it as an address card!
By handing it over, you are telling the function: 'Here's where that value sits in memory; please go get it yourself and change it if you need to!'
If you write a in the function, it is the adress; if you write a*, it is the value, that's living at that adress.
So by writing *a = whatever, you are taking the adress card, looking up the place and change what you find there.
+ 1
I think only a global variable (sitting in the global space) is global, because it can be freely accessed by *everybody*.
Passing a value via pointer to a function is more like granting this and only this function special privileges.
And I'd say the pointer itself is local (you can only use the name inside the function); but it points to a value that hasn't been defined in this area.
0
I have this code here
#include <stdio.h>
void square (int*);
int main(){
int n = 7;
square (&n);
printf ("%i %p\n",n,&n);
return 0;
}
void square (int *a){
printf ("%p\n",a);
*a = *a * *a;
}
Given the code above, I'm really confused why the variable n becomes 49 instead of 7. I assumed that n will remain 7 because the function void square returns nothing