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 ofa
into the memoryptr
points to". Note thatint *ptr;
is not initialized, so you're writing to a random memory location.- Thus,
*ptr
is that address ofa
:(size_t)&a == 634927948
.
- Thus,
int *ptr=&a;
means "ptr
is a pointer that points to the memory wherea
is located".- Thus,
*ptr
is the value at the address ofa
, which isa == 10
itself
- 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
.