线程断点在数组赋值

时间:2015-05-22 05:36:25

标签: c++ arrays random

我试图根据你输入的值创建一个(n x n)大的数组,然后用随机整数填充该数组。你能帮我解决两个问题吗?

  1. 任何n大于4的值都会在显示时出现错误"在最后一行中,如果我显示的是什么值,如果它不是一个错误它是相同的,并且像一个巨大的东西,如20019238394

  2. 为什么它会一直创建相同的数字?它不会产生新的随机数吗?

    #include <iostream>
    #include <string>
    #include <cmath>
    #include <cstdlib>
    #include <time.h>
    using namespace std;
    
    
    int arrayCreate(int);
    
    int main(int argc, const char * argv[]) {
    
    int n;
    cout << "enter how big your array is (n) , it will be shown as (n x   n)" << endl;
    
    cin >> n;
    cout << "------------------------------" << endl;
    
    arrayCreate(n);
    
    
    
    return 0;
    }
    
    int arrayCreate(int n){
    
        srand (time(NULL));
    
        int y=0, x=0;
        int original[x][y];
    //putting in random values
    
    
      for (int y=0; y< n; y++){
    
      for (int x=0; x< n; x++){
        int check = (rand() % 9 + 1);
            if (check < 10)
            original[x][y] = check;
            else
            cout << "error";
    }
    
    }
    //displaying those values
        for (y=0; y<n; y++){
        for (x=0; x<n; x++){
            if (original[x][y] < 10)
        cout << original[x][y] << " ";
            else
            cout << "error at display";
    }
    
    
        cout << "            y is " << y << endl;}
    
    
    
    
    return original[x][y];
    }
    

2 个答案:

答案 0 :(得分:0)

您正在声明大小为[0] [0]的数组。你想要的是size [n] [n]。

结果,您正在写入未分配的内存。纠正:

int original[n][n];

应该适合你。

答案 1 :(得分:0)

创建新数组时,您应该在堆上分配它,因此它将是:

int** original = new int* [n]; // creates column
for(int i=0; i<n; i++)
    original[i] = new int [n]; // creates rows

然后当它不再需要时,必须释放内存

for(int i=0; i<n; i++)
    delete original[i];

delete original;
相关问题