I am facing a problem with allocation of two dimensional char array. The problem statement requires me to get the number of rows and columns of the array from a file. I have saved the rows in "rows" and columns in "columns", both of type int.

Here is how i initialized the array.

char *array;

array = new char [rows][columns];

The error I get is "non constant expression as array bound".

I know what constant expression means. But I am unable to figure out the way to make a 2d dynamic array by getting its size from the file.

Please help me with this thing.

I will appreciate this if you tell me how to make a dynamic 2d char array by getting the size of it from a file.



Recommended Answers

All 3 Replies

I really never use arrays, I go for the vector of vectors

vector<vector<char> > array(columns);
for(unsigned int i = 0; i < columns; i++)
vector<char> RowVector(rows);
// ... fill the row vector ...

If you want to use an actually array you have to use "new", because as it's telling you, you aren't allowed to determine the size of an array declared like you were doing it at runtime.

>>char *array;
That is not a 2-dimensional array. char **array is how to declare it, using two stars not just one.

Here is one way to initialize it

char **array = 0;
array = new char*[rows];
for(int i = 0; i < rows; i++)
    array[i] = new char[columns];

Thanks Ancient Dragon.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.