Pointer in c. Why is the output = 41? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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; }

26th Jan 2019, 2:43 PM
Zhenis Otarbay
Zhenis Otarbay - avatar
2 Answers
+ 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
26th Jan 2019, 2:51 PM
Anna
Anna - avatar
+ 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.
26th Jan 2019, 5:40 PM
Felix Pernat
Felix Pernat - avatar