C中字符的大小

And*_*̷y̷ 1 c sizeof char

我有:

#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)

  • 当您想要获取字符串中的字节数时,不应使用“sizeof”。`sizeof` 只能用在数组上。字符串并不总是数组,它可能是指针。 (2认同)
  • 还有c post 中的c++ 语法吗? (2认同)

rjz*_*rjz 5

由于C字符串以a结尾\0,因此字符串的大小始终为(表观)长度+ 1.