为什么二维数组上的 strcpy 代码会生成错误的输出?

0 c

我尝试运行二维字符数组(字符串数组)的代码,根据编译器和网站,代码显示的垃圾值约为 10x25-10x40(字符串大小)。

#include<stdio.h>
#include<string.h>

int main()
{
    int n=0;
    char name[10][30];
    char e[20];
    int i;
    for(i = 0; i < 30; i++)
    {
        strcpy(name[i],"0");
    }
    for(i = 0; i < 30; i++)
    {
        printf("\n%s",name[i]);
    }
}
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 5

问题是你超出了数组的范围:

char name[10][30];
int i;
for( i=0;i<30;i++)
{
    strcpy(name[i],"0");
}
Run Code Online (Sandbox Code Playgroud)

此处,您对仅包含 10 个元素的数组进行了 30 次迭代。

  • 是的。请注意,在“char name[10][30];”中,10 是字符串的数量,30 是每个字符串的长度。 (3认同)