Tag: indexoutofboundsexception

当我访问数组的超出边界元素时,为什么不会出现运行时错误?

在下面的代码中,我尝试访问数组的’-1’元素,我没有得到任何运行时错误。 #include int A[10] = {0}; int main(){ A[-1] += 12; printf(“%d”,A[-1]); return 0; } 当我运行代码时,它输出12表示它正在向不存在的A [-1]添加12。 直到今天每当我试图访问越界元素时,我都遇到了运行时错误。 我以前从未尝试过简单的代码。 任何人都可以解释为什么我的代码成功运行? 我在我的计算机上运行它,也在ideone上运行它,在它成功运行的两种情况下。

(生命游戏)如何循环遍历矩阵的外层而不检查它的外部,同时检查邻居?

矩阵中的每个点代表一个生命或死亡的细胞。 我必须计算每个单元格中有多少个ALIVE邻居。 我有一个function,但它检查边界外的单元格。我不知道如何在不执行大量if-else语句的情况下同时检查邻居并跟踪边缘。 void Neighbours(int rows, int cols, cell world[rows][cols], int neighbors[rows][cols]) { //Loop through each cell in the matrix. for(int rCell = 0; rCell < rows; rCell++){ for(int cCell = 0; cCell < cols; cCell++) { //Reset neighbor count for each cell. neighbors[rCell][cCell] = 0; //Check cell status in cell's vicinity of each cell. […]

访问超出内存后,分段错误不会立即出现

我编写了这段代码并且期待一个段落故障,但似乎我被允许访问我不应该访问的内存块。 #include int main() { int tab[1]; tab[0]=42; int i; //Expecting Seg Fault from i==1… for(i=0;;i++) { printf(“%d \t %d \n”, i, tab[i]); } return 0; } 我正在编译使用: gcc -Wall -Wextra my_code.c -o segfault && ./segfault 执行后,变量i在得到分段错误之前达到1000的值。 我的问题是:为什么我能够阅读tab到目前为止? PS:使用#include 并声明int * tab = (int*)malloc(sizeof(int)); 什么都不改变…… 谢谢,最好的。