为什么这个数组分配给非指定数组?

Sri*_*adh 1 c c++ arrays undefined-behavior

/*我观察到的是:

  1. 当我给b(数组)提供类似"ab"的字符串时
    输出为:"ab""help""dude"
  2. 当我给"abc"
    然后输出是:"abc""""dude"
  3. 如果我给"abcd",那么输出是:"abc""d""dude"

    等等*/

       #include<stdio.h>
       main()
       {
            char a[5]="help",b[3],c[10]="dude";
         scanf("%s",b);
         printf("\t%s",b); 
         printf("\t%s",a);
         printf("\t%s",c);
       }
    
       /* what i dont get is :
        Here iam  gaving a string to b(array),  why, if the string has more than the  
        required no. of charecters, its printing those charecters in other arrays 
       (though i had not assiged scanf to other arrays )?   
    
    Run Code Online (Sandbox Code Playgroud)

Flo*_*ris 5

请记住,C中的字符串需要空终止符.如果没有空间,打印将继续"到下一个nul".以下是您的内存在初始化中的表现:

h  e  l  p \0 \0 \0 \0  d  u  d  e \0
^             ^         ^
a             b         c
Run Code Online (Sandbox Code Playgroud)

当您在ab指向的位置读取字符串时b:

h  e  l  p \0  a  b \0  d  u  d  e \0
^              ^        ^
a              b        c
Run Code Online (Sandbox Code Playgroud)

一切都很好.但是abc给出:

h  e  l  p \0  a  b  c \0  u  d  e \0
^              ^        ^
a              b        c
Run Code Online (Sandbox Code Playgroud)

当你打印时,b你会得到abc; 打印c会让你一无所获(第一个角色'\0').

最后,输入abcd你得到

h  e  l  p \0  a  b  c  d \0  d  e \0
^              ^        ^
a              b        c
Run Code Online (Sandbox Code Playgroud)

打印c将会产生"d"- 正如您所看到的那样.

实际上,事物存储在内存中的顺序不是"定义的",尽管通常编译器会执行与上面类似的操作.因此,虽然您知道不能写入不属于您的内存,但您无法确定在执行此操作时会发生什么(如您的情况).这就是为什么它被称为"未定义的行为".你不能依赖其他编译器给你相同的结果 - 甚至相同的编译器给你相同的结果......

合理?

当然,解决方案是分配更多空间b.这将导致更多和'\0'之间,并且没有任何被覆盖.bc

编辑 - 我刚才意识到,它的存储顺序似乎ba我刚刚描述的顺序相反 - 因为它a不会c被覆盖.这表明编译器订购的东西非常愉快,并且当我写详细的答案时我应该戴上眼镜.但原则完全一样 - 所以我会"把剩下的作为学生的练习".