#include <stdio.h>
int main(void)
{
char var = 'z';
printf("[buf]: %s \n", &var); // the output is z~~~~~, but the first char of output is only z. why??
}
I wonder why &a(Data type: char) is printed as value not address, using %s
90 Views Asked by y J. At
2
There are 2 best solutions below
0
On
%s tells printf to accept a pointer to the first character of a string and to print that string, up to the null character that indicates its end. Since you pass the address of a single character, printf prints that and continues looking in memory for more characters to print, until it finds a byte containing zero. For %s, when you pass a pointer to a single character, rather than an array of characters terminated by a null character, the behavior is not defined by the C standard.
To print an address, use %p and convert the pointer to void *:
printf("%p\n", (void *) &var);
The conversion specifier
sis designed to output strings (or their parts): sequences of characters terminated by the zero character'\0'.To output the address of an object there is the conversion specifier
p.Here is a demonstrative program.
The program output might look like
As for the code in your question then it has undefined behavior because the expression
&vardoes not point to a string because the variablevaris defined likeIf you want to output its address then you can do it as