+ 1
printf in using memory
When we scanf we have & to denote the address, but why is & being used for printf?
6 Antworten
+ 4
scanf() needs to access memory address of the variable because it have to make changes to the original variable, but printf() is just printing the value thus is passed by value instead of reference.
But if you pass a variable to printf() like this:-
printf ("%d",&a)
Then in this case it will be displaying the memory address of the variable "a".
You must note that you are passing the memory address of "a" to the function printf() by value thus any changes to it will not affect original memory location
+ 3
scanf("%d %d", &a, &b); printf("%d %d", a, b);
As a and b above are two variable and each has their own address assigned but instead of a and b, we send the address of a and b respectively. The reason is, scanf() needs to modify values of a and b and but they are local to scanf(). So in order to reflect changes in the variable a and b of the main function, we need to pass addresses of them. We cannot simply pass them by value.
But in case of printf function as we are only going to print the values of the variables in output console, there are no changes going to be made in variable a and b’s values. So it is not required to send their addresses.
+ 2
Shreya,
Do you have an example of printf() usage with & (address-of) operator? just curious ...
+ 2
Counterpoint: With "%s" in scanf, & is not used on the string variable. For example, char strBuffer[50]; scanf("%s", strBuffer); is correct. The string variable is already a char pointer to the first element in the array.
0
printf() - The C library function int printf(const char *format, ...) sends formatted output to stdout
0
scanf read the input from standard input, it requires an address where to store the taken input..
In Printf , we print values so just specifying variable will return value. If we put &variable then it return address, not value.
So variable return value where as &variable return location...
to print location in printf, we use &..