Home > Mobile >  Why is this happening to C pointers?
Why is this happening to C pointers?

Time:05-31

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

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.

  • Related