[英]'stack smashing detected abc2 terminated Aborted' shows when looping an array
When I try to compile the below code terminal says stack smashing detected abc2 terminated Aborted (core dumped)
.当我尝试编译以下代码时,终端说stack smashing detected abc2 terminated Aborted (core dumped)
。 This error shows when for loop going through the two dimensional array .此错误显示 for 循环何时遍历二维数组。
What I want to do is get user input to first column using cin>>arr[0][i];
我想要做的是使用cin>>arr[0][i];
获取用户输入到第一列cin>>arr[0][i];
and 0 for every other columns using arr[i+1][r]=0;
使用arr[i+1][r]=0;
表示每隔一arr[i+1][r]=0;
. .
#include <iostream>
using namespace std;
void displayArray(int arr[][4],int row,int col);
int main(){
int arr[3][4];
for(int i=0;i<4;i++){
cout<<"enter value ";
cin>>arr[0][i];
for(int r=0;r<3;r++){
arr[i+1][r]=0;
}
}
displayArray(arr,3,4);
return 0;
}
void displayArray(int arr[][4],int row,int col){
for(int i=0;i<row;i++){
for(int r=0;r<col;r++){
cout<<arr[i][r]<<" ";
}cout<<endl;
}
}
You are going beyond the bounds of your array here:您在这里超出了数组的范围:
int arr[3][4];
for(int i=0;i<4;i++){
//...
arr[i+1][r]=0; // <-- i+1 when i == 2 is going to give trouble
//...
}
If i >= 2
, you're writing to arr[3]
, arr[4]
, etc. This is a memory overwrite and the behavior then becomes undefined.如果i >= 2
,则您正在写入arr[3]
、 arr[4]
等。这是内存覆盖,然后行为变得未定义。
Obviously the fix is either to throttle the loop back so that i
is always less than 2, or your array's first dimension needs to be increased from 2 to a bigger number.显然,解决方法是限制循环,使i
始终小于 2,或者您的数组的第一维需要从 2 增加到更大的数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.