Why is it that I have to do a reference for &x when usingCode:int main()
{
int x;
x = 10;
printf("%d\n", x);
scanf("%d", &x);
printf("%d", x);
}
scanf("%d", &x);
Printable View
Why is it that I have to do a reference for &x when usingCode:int main()
{
int x;
x = 10;
printf("%d\n", x);
scanf("%d", &x);
printf("%d", x);
}
scanf("%d", &x);
You need to pass a pointer in order for scanf to modify the object through the pointer.
By the way, post your code as plain text without special markup other than code tags. The code tags will trigger its own syntax highlighting and line numbering.
There are no references in c.
scanf takes a const pointer to char as it's first argument, so you must either give it a pointer to a char or the address of a char, which for all intents and purposes, is the same thing.
You obtain the address of a variable with the & operator. Which is what you are doing there.
Another way would be.
Code:int x = 10;
int_ptr y = &x;
scanf("%d\n", y);