+ 7
Pointer in c. Why is the output = 41?
#include <stdio.h> int main() { int *p=(int*)malloc(sizeof(int)); *p=42; int* v=p; *v=41; printf("%d",*p); free(p); return 0; }
2 Respuestas
+ 4
You create a pointer v that points to the memory location of p, so when you change the value of the memory location that v points to, p will be changed accordingly
+ 2
The values of pointers v and p are memory adresses. When v is assigned the value of p, they point on the same memory slot.
The preceeding asterix (*v = . .) means "write '...' into the memory slot v is pointing to". As p also points to the same slot (adress), eventually *p (reads like "the value at memory adress p") outputs that new value.
C is awesome! Happy coding :)
Edit: Anna, v does not 'point to the memory location of p' ( v != &p ), instead v points to the memory location p is also pointing to (you might want to clearify that in your answer). Saludos.