+ 2
Need help with pointers in C
#include<stdio.h> void f(int *p, int *q) { p = q; *p = 3; } int i = 0, j = 10; int main() { f(&i, &j); printf("%d %d \n", i, j); getchar(); return 0; } i thought on execution answer should be 3 3 but,when executed the answer is 0 3 Can someone explain??
2 Respostas
+ 2
At the beginning you have i and j two variables in different area of memory.
---------------------
0x001 | i | 0
---------------------
0x002 | j | 10
---------------------
Then you call f and you have p pointing to i an q pointing to j
---------------------
0x001 | i | 0
---------------------
0x002 | j | 10
---------------------
0x003 | p | 0x001
---------------------
0x004 | q | 0x002
---------------------
Then p = q so, variable p is pointing to 0x002 (variable j), and now no one is pointing to i
---------------------
0x001 | i | 0
---------------------
0x002 | j | 10
---------------------
0x003 | p | 0x002
---------------------
0x004 | q | 0x002
---------------------
Then you modify the value of the variable pointed by p (*p = 3;) and this variable is allocated in memory 0x002( variable j) so j will be equal to 3
---------------------
0x001 | i | 0
---------------------
0x002 | j | 3
---------------------
0x003 | p | 0x002
---------------------
0x004 | q | 0x002
---------------------
Then you print i = 0 and j = 3
+ 1
Start with tell that a pointer is a simple variable that contains adresses... Ok now go to first line of f function body...
p=q;
Here you tell "assign q value (an adress) to p var".. Now p and q have same value (adress)...
*p=3;
Here you tell "derefence p (access to memory) and assign 3 as value (at adress/value contained in p). What happen? you change the int value at adress p (and q) which is second adress passed to function... The first adress is untouched and hence unmodified... You can obtain wanted result if:
- remove first line (p=q)
- add follow statement: *q=3;