Search code examples
cprintfscanf

printf returning 6422044 for the value of variable


Question

Basically, I have a simple C code to return the value of a variable, but, if I change the & of the scanf() and the printf the returned value of variables is changed. What is the technical explanation for this event?

(input: 3) printf returning: 3

#include <stdio.h>
#include <stdlib.h>

void main(){
    int x = 1;
    scanf("%d", &x);
    printf("%d", x);
}

(input: 3) printf returning: 6422044

#include <stdio.h>
#include <stdlib.h>

void main(){
    int x = 1;
    scanf("%d", &x);
    printf("%d", &x);
}

(input: 3) printf returning: (nothing)

#include <stdio.h>
#include <stdlib.h>

void main(){
    int x = 1;
    scanf("%d", x);
    printf("%d", &x);
}

Solution

  • With printf("%d", &x);, you pass the address of x where printf expects an int. The C standard does not define the behavior when you do this. A common result is that the address, or part of it, is interpreted as an int and printed, so 6422044 may be part of the address of x in memory.

    With scanf("%d", x);, you pass the int value of x, 1, where scanf expects the address of an int. The C standard does not define the behavior when you do this. A common result is that the int is reinterpreted as an address and scanf attempts to write to that address. The address 1 is likely not mapped as accessible by your process, causing your process to terminate. This would result in no output from the process and also should have resulted in some error message about program terminating. If you executed the program in an IDE, you may have missed this.