Search code examples
cpointerscpu-architecture

Why declaring a variable p as int and using it in scanf is ok but not ok if i don't use scanf?


learning C here. I am currently in topic of pointers and i am confused about somethings.

int c;
printf("insert the first number of your age");
scanf("%d", &c);

The one above works ok but not

int c;
int p = 1;
c = &p;

And also, why don't we use & for strings. As in for example

char val[2];
printf("please insert your Blood type");
scanf("%c",val);

I have a decent knowledge of computer architecture. If it can be related, it would be very nice if you explain it to me by connecting it to microinstructions and the CDU(control decoding unit) by relating it also to external buses like MAR and MDR


Solution

    • In scanf("%d", &c); you pass a pointer to int to the scanf function so that it can write into the memory of the variable the pointer is pointing at (that is, c).

    • In c = &p; you try to assign an int* to an int. These are incompatible types. An int* points at an int, but isn't an int.

    • In scanf("%c",val); the char array val decays into a pointer to the first element in the array. The type is a char* - which is exactly what %c requires to write a char into the memory provided. Had the variable var been a char instead of an array of char, you would have needed scanf("%c", &val); to provide a char*.

    it would be very nice if you explain it to me by connecting it to microinstructions and the CDU(control decoding unit) by relating it also to external buses like MAR and MDR

    I don't see the relevance. You are using a language that provides a set of rules and abstractions from what goes on underneath. The scanf and pointer operations described works the same way in any conforming C implementation regardless of what machine code, micro instructions and buses that is required for the C code to work on the specific target platform. Also, I know very little about those things.