When I'm using this code, the output is incorrect.
#include <stdio.h>
int main() {
int a, *ptr;
a=10;
*ptr=&a;
printf("%d",*ptr);
return 0;
}
Output is: 634927948
But when I'm using this code, It's giving the correct output.
#include <stdio.h>
int main() {
int a=10;
int *ptr=&a;
printf("%d",*ptr);
return 0;
}
Output is: 10
CodePudding user response:
*ptr=&a;means "write the address ofainto the memoryptrpoints to". Note thatint *ptr;is not initialized, so you're writing to a random memory location.- Thus,
*ptris that address ofa:(size_t)&a == 634927948.
- Thus,
int *ptr=&a;means "ptris a pointer that points to the memory whereais located".- Thus,
*ptris the value at the address ofa, which isa == 10itself
- Thus,
CodePudding user response:
The following line is dereferencing the pointer before assignment. The value at the memory location of ptr is assigned the memory address of a.
*ptr = &a;
Instead the line should be :
ptr = &a;
ptr will point to the memory location of a.
If you use :
*ptr = a;
The memory location that the pointer is pointing to (already) will be assigned the value of a.
