#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??
}

- 301,070
- 26
- 186
- 335

- 131
- 4
-
2`%s` is for strings, so how would that print an address anyway? Also, this is undefined behavior. There's no NUL terminator after `z`. – mediocrevegetable1 May 09 '21 at 11:44
2 Answers
The conversion specifier s
is 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.
#include <stdio.h>
int main(void)
{
char s[] = "Hello";
printf( "%s\n", s );
printf( "%p\n", ( void * )s );
return 0;
}
The program output might look like
Hello
0x7ffc86fe4372
As for the code in your question then it has undefined behavior because the expression &var
does not point to a string because the variable var
is defined like
char var = 'z';
If you want to output its address then you can do it as
printf("[buf]: %p \n", ( void * )&var);

- 301,070
- 26
- 186
- 335
%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);

- 195,579
- 13
- 168
- 312