简体   繁体   English

为什么要打印完整的字符数组而不是第一个字符?

[英]Why the complete character array is getting printed not the first character?

This is the source code 这是源代码

char target[80]="hello", *tar;
tar=⌖
printf("%s",tar);  //printing hello

tar is getting the address of target[0] then why it is printing the whole character array. tar正在获取target[0]的地址,然后为什么要打印整个字符数组。

when u say %s and specify a starting memory(or any intermediate) of the string it gets printed till it encounters '\\0' character. 当您说%s并指定字符串的开始存储(或任何中间)时,它将被打印直到遇到'\\ 0'字符。

consider 考虑

    char *name = "Hello";

will be stored internally as Hello\\0 将在内部存储为Hello \\ 0

so if u need a single character go for %c. 因此,如果您需要一个字符,请使用%c。

使用%c打印单个字符,使用%s打印字符串。

C strings are null terminated. C字符串以null结尾。 When you pass the address of the first character in an array of characters representing a string to printf and tell it to format the output as a string using %s , it will print all of the characters beginning at the address of the first character until a null (NUL) character, '\\0' , is reached. 当您将代表字符串的字符数组中的第一个字符的地址传递给printf并告诉它使用%s将输出格式化为字符串时,它将打印从第一个字符的地址开始的所有字符,直到出现空(NUL)字符'\\0'

%s indicates printing characters between the character 'tar' points to and next '\\0' . %s表示在字符“ tar”指向和下一个“ \\ 0”之间打印字符。

printf("%c",*tar); printf(“%c”,* tar);

will print what you need. 将打印您所需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM