I am new to pointer to class.I write simple code to show my question.
Why can p->num set value in f2? Pointer p isn't like n ? Just a local variable?
Aren't both n1 and p2 's scope only in f1 and f2 separately ? thanks
What is different between them!
class Node{
public:
int num;
Node* next;
};
void f1(Node n1){
n1.num = 50;
}
void f2(Node*p2){
p2->num= 100;
}
int main(){
Node n;
f1(n);
cout<<n.num<<endl;//output 0
Node*p;
f2(p);
cout<<p->num<<endl;//output 100
return 0;
}
Node*p; f2(p);is undefined behavior as-is. Yourpdoesn't point anywhere. Also, use whitespace. Seriously. Code w/o whitespace is hard to read. As to why can a value be modified through a pointer: because that's how memory access works. You grab an address, dereference it, write to the memory at that address.pis indeterminate. It has no stated value. Using it for evaluation in any way is undefined behavior.