繁体   English   中英

中止(倾销的核心)

[英]Aborted (dumped core)

./product -rows 4 -cols 4

我收到此错误:

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Abort (core dumped)

这是我的代码。

#include <iostream>
#include <stdlib.h>

using namespace std;


int **create_array(int rows, int cols){
   int x, y;
   int **array = new int *[rows];
    for(int i = 0; i < cols; i++){
       array[i] = new int[cols];
    }
    array[x][y] = 1+rand()%100;
    cout << array << endl;
    return array;
}  
int main(int argc, char *argv[]){
    int rows, cols;
    int **my_array = create_array(rows, cols);

    return 0;
}

我看不到在main中将变量rowscols初始化的位置。

解决此问题后, create_array中的xy遇到相同的问题。 如果对象是用伪随机值填充数组,则不需要x因为i已经在遍历2D数组(顺便说一句,其基于指针矢量的表示称为Iliffe矢量 )。 您只需要引入一些j可以遍历数组的每一行。 j将进入嵌套在现有循环内的循环中:

for(int i = 0; i < rows; i++){
   array[i] = new int[cols];       // allocate row
   for (int j = 0; i < cols; j++)  // loop over it and fill it
     array[i][j] = 1 + rand()%100;
}

还有另一个问题,您的主循环(应该分配数组的 )将i0循环到i < cols 这应该是i < rows 在循环内部,您分配了一个大小为[cols] ,这是正确的。 如果您仔细观察,在上面的摘要中,我已进行了更正。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM