2016-12-01 43 views
-1

我想创建一个二维数组,其大小只在运行时已知。试图创建一个二维数组,其大小只有在运行时已知c +

我试着做以下几点:

std::ifstream myFile; 
myFile.open("input.txt",std::ios::in); 
int num_cols; 
myFile >> num_cols; 
int num_rows = 10; 

int *HArray; 
HArray = (int*) malloc(sizeof(int)*num_cols*num_rows); 

但当我尝试这个办法:

for (int i = 0; i < num_rows; i++) { 
    for(int j = 0; j < num_cols; j++) { 
     HArray[i][j] = i*j + 34*j; 
    } 
} 

我在编译过程中出现以下错误:


错误2错误C2109:下标需要数组或指针类型


如何分配的内存HArray使得我可以使用指数为[i] [j]来访问和将值分配给该数组?

我试过了@Uri的答案可用here,但是程序立即崩溃了,我也不是很了解发生了什么事情。

编辑:

我决定使用以下

std::vector<std::vector<int>> HArray(num_rows, std::vector<int>(num_cols)); 
+2

I *高度开始*建议你阅读一本好的C++书。通过试验和错误学习C++或从网络中随机选择的片段将结束不佳,相信我。 –

+0

你知道行数吗? –

+0

@BaummitAugen,但它不是随机片段,它是一个很好的stackoverflow答案... –

回答

0
#include <iostream> 
#include <string> 
#include <fstream> 


int main() 
{ 
    std::ifstream myFile; 
    myFile.open("input.txt", std::ios::in); 
    int num_cols; 
    myFile >> num_cols; 
    int num_rows = 10; 


    int** HArray = new int*[num_rows]; 
    for (int i = 0; i < num_rows; ++i) 
    { 
     HArray[i] = new int[num_cols]; 
    } 

    return 0; 
} 
-1

可用在C创建一个二维数组++从双指针

int  ** matrix; 
matrix = new int * [num_cols]; 
for (int i = 0; i < num_cols; i++){ 
    matrix[i] = new int [num_rows]; 
} 
+0

“双指针”具有误导性,它是指向int的指针的指针,而不是指向double的指针。 – Robert

+0

另一个问题是,如果矩阵没有参差不齐(不同的行大小),这是使用循环创建一个矩阵的最糟糕的方式(尽管这看起来是最显示的方式)。为了更有效地做到这一点,[看到这个答案](http://stackoverflow.com/questions/21943621/how-to-create-a-contiguous-2d-array-in-c/21​​944048#21944048) – PaulMcKenzie

相关问题