I know this is the incorrect way to use scanf( ). But I want an expert in C to answer this question:
#include <stdio.h>
int main(int argc, char *argv[])
{
int *a;
printf("please input one number:\n");
scanf("%d", &a);
printf("your input is %d\n", a);
return 0;
}
the output:
please input one number:
30
your input is 30
since *a already exist, it won't bring segment fault while executing. and scanf( ) magically fill correct data into *a, made (int *) into (int); then printf( ) will output correctly.
I think this code could work because of sizeof(int*) and sizeof(int) is the same value on my system. So I also do check some type size on my system:
sizeof(short) return 2
sizeof(short*) return 4
sizeof(int) return 4
sizeof(int*) return 4
sizeof(long) return 4
sizeof(long*) return 4
sizeof(float) return 4
sizeof(float*) return 4
sizeof(double) return 8
sizeof(double*) return 4
sizeof(char) return 1
sizeof(char*) return 4
seems this code could also work when float, but it doesn't. the code I try is here:
#include <stdio.h>
int main(int argc, char *argv[])
{
float *a;
printf("please input one number:\n");
scanf("%f", &a);
printf("your input is %f\n", a);
return 0;
}
the output:
please input one number:
3.5
your input is -0.034267
scanf( ) should work since I use %f when calling scanf( ). since I still give it a 4-bytes memory address.
I can't figure it out. could someone who is knowing the whole scanf( ) thing explain why these two codes(almost the same) works different way?