Reputation: 3
I would like to put first 7 elements of buf[20] into char A to G. I expect the result could be 1 H, 2 e, 3 l, 4 l,5 o, 6 ,7 W
, but what I got is 1 H,2 e olWH,3 lWH,4 le olWH,5 olWH,6 olWH,7 WH
. Could anyone explain this, please?
#include <stdio.h>
char buf[20]="Hello World";
char A,B,C,D,E,F,G;
int main()
{
A=buf[0];
B=buf[1];
C=buf[2];
D=buf[3];
E=buf[4];
F=buf[5];
G=buf[6];
printf("1 %s,2 %s,3 %s,4 %s,5 %s,6 %s,7 %s",&A,&B,&C,&D,&E,&F,&G);
return 0;
}
Upvotes: 0
Views: 76
Reputation: 138171
Use %c
and A
-G
instead of %s
and &A
-&G
.
%s
is the printf format for strings, and %c
is the printf format for characters.
A C string is the memory address of a sequence of characters that is terminated by the special character '\0'
. buf
is a string, but A through G are just one character each and their address can't be treated as a string.
Upvotes: 4