我有:
#include <stdio.h>
int main()
{
char ch[] = "Hello";
char wd[] = "World";
char ex[] = "!";
printf("The size of a char: %ld\n",sizeof(char));
printf("The size of ch[]: %ld\n",sizeof(ch));
printf("The size of ex[]: %ld\n",sizeof(ex));
printf("The size of wd[]: %ld\n",sizeof(wd));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
产量:
The size of a char: 1
The size of ch[]: 6
The size of ex[]: 2
The size of wd[]: 6
Run Code Online (Sandbox Code Playgroud)
我的问题:由于char的大小是1个字节,为什么ch []的大小不是5个字节?因为它有5个字符(H,e,l,l和o)
与wd []和ex []相同.这里发生了什么?
对不起,如果这是一个很容易的,但我是C的新手.
小智 7
在这份声明中:
char ch[] = "Hello";
Run Code Online (Sandbox Code Playgroud)
将空终止的字符串文字复制到ch. 因此有六个字符,包括 NUL 终止符。请注意,strlen不会计算NUL 终止符。
char c[] = "Hello";
printf("%s", c);
Run Code Online (Sandbox Code Playgroud)
strlen因此,当您需要字符串的大小以及sizeof字符串中的字节数时,应该使用。请注意,如果您有字符指针而不是数组,则它将没有大小信息。
char* ptr = "Hello";
sizeof(ptr); // size of a character pointer
sizeof(*ptr); // size of a char
strlen(ptr);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2772 次 |
| 最近记录: |