Hello,
I was doing some experiments with pointer and wrote the following code :-
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *p;
int *q;
p = (int*) malloc (sizeof(int) * 3);
printf ("Address: &p = %u, p = %u\n", &p, p);
p[0] = 10;
p[1] = 20;
p[2] = 30;
q = p;
printf ("&q = %u, q = %u\n", &q, q);
free(p);
printf ("After Freeing p:\n&q = %u, q = %u\n", &q, q);
printf ("%d %d %d\n", q[0], q[1], q[2]);
return 0;
}
I have allocated the memory to pointer p for 3 integers and then i assigned them values 10, 20, 30. Now for pointer q, I set it to point to the address pointed by p. Now I freed pointer p's allocated memory. After freeing, q will still point to the same address. Now when I print the values again through q, the first value q[0] comes out to be 0 and remaining the same. Why does it happen? Any Idea.
Thanks and Best Regards,
Aakash Johari