-1

I'm trying to create a 2D array in c++ whose size is only known at runtime.

I tried doing the following:

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);

But when I try this:

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

I get the following error during compilation:


Error 2 error C2109: subscript requires array or pointer type


How do I allocate the memory for HArray such that I can use the indices [i][j] to access and assign values to the array?

I tried following @Uri's answer available here, but the program immediately crashes, and I didn't really understand what was going on either.

EDIT:

I decided to use the following

std::vector<std::vector<int>> HArray(num_rows, std::vector<int>(num_cols));
Community
  • 1
  • 1
Veridian
  • 3,531
  • 12
  • 46
  • 80
  • 2
    I *highly* recommend you read a good C++ book. Learning C++ by trial and error or from random snippets from the web will end poorly, trust me. – Baum mit Augen Dec 01 '16 at 21:11
  • do you know the number of rows? – Jean-François Fabre Dec 01 '16 at 21:11
  • @BaummitAugen but it's not random snippets, it's a good stackoverflow answer... – Jean-François Fabre Dec 01 '16 at 21:12
  • @Jean-FrançoisFabre It's a random snippet if you don't understand what's going on. – Baum mit Augen Dec 01 '16 at 21:12
  • 1
    @Veridian you've got a 1D array here. If you really want a 2D array, [edit] your post and show us what you tried and try to figure out why it crashes. – Jean-François Fabre Dec 01 '16 at 21:13
  • @BaummitAugen I was being helf-sarcastic BTW. I think that the OP has adapted the answer and failed doing so. Now he has to edit his post to show his other attempt. Yes, it should use `new` or even better: `std::vector` – Jean-François Fabre Dec 01 '16 at 21:14
  • 1
    `std::vector> v(num_rows, std::vector(num_cols));` might solve your issue. – Jarod42 Dec 01 '16 at 21:14
  • @Jean-FrançoisFabre Alright. My first comment still very much applies here. :) – Baum mit Augen Dec 01 '16 at 21:16
  • @Jarod42, if he's doing this for a course or something -- which I would guess he is because this is a basic problem -- he might be required to use arrays instead of vectors. OP, just some general guiding advice, the definition of a 2D Array is an array-of-arrays. Go from there. – Spencer D Dec 01 '16 at 21:18
  • @Veridian I don't think Spencer was condescending. We have lots of questions where the instructions of the teacher was "not to use vectors" (yes, it kills the fun :)) – Jean-François Fabre Dec 01 '16 at 21:22
  • @Veridian: [Demo](https://ideone.com/lDzXjE). – Jarod42 Dec 01 '16 at 21:22
  • @Veridian - [Already answered here](http://stackoverflow.com/questions/21943621/how-to-create-a-contiguous-2d-array-in-c/21944048#21944048) – PaulMcKenzie Dec 01 '16 at 21:30
  • @PaulMcKenzie: that's for C. For C++ answered here: http://stackoverflow.com/questions/936687/how-do-i-declare-a-2d-array-in-c-using-new – Jean-François Fabre Dec 01 '16 at 21:32
  • @Jean-FrançoisFabre That's actually C++ as it templatizes the data type of the 2D array. I'm assuming the OP is stuck using dynamic allocation and can't use `std::vector`. – PaulMcKenzie Dec 01 '16 at 21:35
  • I'm not stuck using anything. I just didn't realize vector was the way to go. Vector worked for me, so thanks to @Jarod42. But if I use 'new', then I have to use 'delete'. When vector, I don't have to do that though, right? – Veridian Dec 01 '16 at 21:36
  • Allocate with malloc(N * M *sizeof(double))> Access with array[y*M] = x; – Malcolm McLean Dec 01 '16 at 21:38
  • @Veridian `vector` deallocates its memory when it goes out of scope. so no need to. That's one of the reasons C++ is better than C. You should use C++ for vectors & strings only, even if you don't use classes. – Jean-François Fabre Dec 01 '16 at 21:39
  • @Jean-FrançoisFabre, thanks for the backup ;) I definitely was not intending to come off as condescending. I simply do not know the OP's experience level nor do I know the constraints (_e.g., cannot use vectors or something_). If this were for a class homework assignment, I wouldn't want to just explicitly give out the answer, because I personally think it is important for students to take the time to think critically, read documentation, and figure things out independently. As such, in the case of a student doing a homework assignment, I prefer to provide a hint rather than an answer. – Spencer D Dec 01 '16 at 21:41

2 Answers2

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;
}
yahiheb
  • 147
  • 9
-1

You can create a 2D array in C++ starting from a double pointer

int     **  matrix;  
matrix = new int * [num_cols];
for (int i = 0; i < num_cols; i++){
    matrix[i] = new int [num_rows];
}
alxreiver
  • 1
  • 1
  • "double pointer" is misleading, it's a pointer to pointer to int, not a pointer to double. – Robert Dec 01 '16 at 21:41
  • Another issue is that if the matrix is not ragged (differing row sizes), this is about the worst way to create one using a loop (even though this seems to be the way that gets presented the most). For a more efficient way of doing this, [see this answer](http://stackoverflow.com/questions/21943621/how-to-create-a-contiguous-2d-array-in-c/21944048#21944048) – PaulMcKenzie Dec 01 '16 at 21:49