C语言中的NUL字符和静态字符数组/字符串文本

C语言中的NUL字符和静态字符数组/字符串文本,c,arrays,char,C,Arrays,Char,我知道字符串在C中以NUL'\0'字节终止。 然而,我不明白的是,为什么字符串文本中的0与堆栈上创建的字符数组中的0的行为不同。当在一个文字中检查NUL终止符时,数组中间的零点不会被处理。 例如: #include <stdio.h> #include <string.h> #include <sys/types.h> int main() { /* here, one would expect strlen to evaluate to 2 */

我知道字符串在C中以NUL
'\0'
字节终止。 然而,我不明白的是,为什么字符串文本中的
0
与堆栈上创建的字符数组中的
0
的行为不同。当在一个文字中检查NUL终止符时,数组中间的零点不会被处理。

例如:

#include <stdio.h>
#include <string.h>
#include <sys/types.h>

int main()
{

    /* here, one would expect strlen to evaluate to 2 */
    char *confusion = "11001";
    size_t len = strlen(confusion);
    printf("length = %zu\n", len); /* why is this == 5, as opposed to 2? */



    /* why is the entire segment printed here, instead of the first two bytes?*/
    char *p = confusion;
    while (*p != '\0')
        putchar(*p++);
    putchar('\n');



    /* this evaluates to true ... OK */
    if ((char)0 == '\0')
        printf("is null\n");


    /* and if we do this ... */
    char s[6];
    s[0] = 1;
    s[1] = 1;
    s[2] = 0;
    s[3] = 0;
    s[4] = 1;
    s[5] = '\0';

    len = strlen(s); /* len == 2, as expected. */
    printf("length = %zu\n", len);

    return 0;
}

为什么会发生这种情况?

'0'和0不是相同的值。(第一个通常是48,尽管从技术上讲,精确值是由实现定义的,并且写48来引用字符“0”被认为是非常糟糕的样式。)


如果“0”以字符串结尾,您将无法在字符串中放入零,这将有点。。。限制。

您可以查看ASCII表(例如)以检查字符“0”和null的确切值

变量“Conflusion”是指向文本字符串字符的指针。 所以记忆看起来像

 [11001\0]
因此,当您打印变量“混淆”时,它将打印所有内容,直到第一个空字符\0为止。
11001中的零不是空的,它们是文字零,因为它被双引号包围

但是,在变量“s”的字符数组赋值中,您将十进制值赋值给0 字符变量。执行此操作时,将为其分配ASCII十进制值0,即空字符的ASCII字符值。因此,字符数组在内存中看起来类似

  [happyface, happyface, NULL]
ASCII字符happyface的ASCII十进制值为1。 所以当你打印的时候,它会把所有内容打印到第一个空值,因此 斯特伦号是2号

这里的诀窍是理解当一个十进制值被分配给一个字符变量时,它实际上被分配给了什么

请尝试以下代码:

 #include <stdio.h>

 int
 main(void)
{
    char c = 0;

    printf( "%c\n", c );  //Prints the ASCII character which is NULL.
    printf( "%d\n", c );  //Prints the decimal value.

    return 0;
#包括
int
主(空)
{
字符c=0;
printf(“%c\n”,c);//打印空的ASCII字符。
printf(“%d\n”,c);//打印十进制值。
返回0;

}

字符串文字是
char
数组!C语言中没有堆栈。指针不是数组。“在这里,人们会认为斯特伦的评价是2”-为什么?看起来似乎有一些关于数组、指针和字符串的错误概念。因为“0”!=0字符
'0'
的值为48()。空终止符“\0”的值为零。
 #include <stdio.h>

 int
 main(void)
{
    char c = 0;

    printf( "%c\n", c );  //Prints the ASCII character which is NULL.
    printf( "%d\n", c );  //Prints the decimal value.

    return 0;