当我使用gcc编译器运行下面的程序时,我的结果是“分割错误: 11",但当我在"https://www.onlinegdb.com/online_c_compiler”上运行同样的程序时,它执行得非常好。我想知道,为什么gcc会在这里抛出分割错误?
#include <stdio.h>
int main(){
typedef int myArray[10];
myArray x = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};//Equivalant to x[10]
myArray y[2]; //equivalant to y[10][2]
int counter = 0;
for(int i = 0; i < 10; i++){
for(int j = 0; j < 2; j++){
//printf("%i %i\n", i, j);
y[i][j] = counter++;
}
}
printf("\n\nElements in array x are\n");
for(int i = 0; i < 10; i++){
printf("x[%i] = %i\n", i, x[i]);
}
printf("\n\nElements in array y are\n");
for(int i = 0; i < 10; i++){
for(int j = 0; j < 2; j++){
printf("y[%i][%i] = %i\t", i, j, y[i][j]);
}
printf("\n");
}
return 0;
}我用的是gcc 4.2.1版。操作系统: MAC
$gcc --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include/c++/4.2.1
Apple LLVM version 10.0.0 (clang-1000.10.44.4)
Target: x86_64-apple-darwin18.2.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin发布于 2019-01-23 22:53:11
这里的评论是错误的:
myArray y[2]; //equivalant to y[10][2]y实际上被定义为:
int y[2][10];即。y有2行,每行10个int。
然后,当您使用从0到9的行索引i和从0到1的列索引来访问y[i][j]时,只要i * ROW_SIZE + j (或i * 10 + j)大于或等于ROW_SIZE * ROW_CNT (或10 * 2),您就会访问超出界限的数组。
例如,y[9][1]尝试访问第10行的第二个值。但是在y中只有2行。
Trying to access an array out of bounds has undefined behavior。Undefined behavior意味着任何事情都可能发生,包括运行正常或崩溃。
要修复您的代码,请按如下方式定义y (以便它与注释匹配):
int y[10][2];https://stackoverflow.com/questions/54329288
复制相似问题