Programmers learn & share
+1 vote
17 views

Problem:

Hello all,
How to declare an array properly in c/c++? I am a new student of c++ and I am trying to declare two-dimensional arrays in my program. Unfortunately, my arrays are not working. Here is my sample code

int row = 5;
int col= 5;
int [row][col];

The above codes throw an error expression must have a constant value c++. What’s wrong with it?

by (12.9k points)   | 17 views

2 Answers

+1 vote

Solution:

You’ve declared the variables row and col as a normal integer type. C++ doesn't allow non-constant values for the size of an array. That's just the way it was designed. In your scenario, you are trying to allocate an array length with unknown value. That’s the reason your compiler can't read the code and gives the error back. For array, you need to specify the length very clearly that the compiler can create the space and allocate the required memory. The compiler cannot make any assumptions about the contents of non-constant variables. So, you may re-write the code again this way

const int row = 5;
const int col= 5;
int myArray[row][col];

This const fixes the size of the array. Now I am sure you understand the problem well. Keep asking.

Thanks

by (55.5k points)  
0 votes

You are trying to declare a two-dimensional array. It is the simplest form of a multidimensional array.

A two-dimensional array is, in essence, is a list of a one-dimensional array.

Declaration:

To declare a two-dimensional integer array of size x and y you have to write as;

Type arrayname [x][y];

Where type can be any valid C++ data type and arrayName will be a valid C++ identifier.

Two-dimensional array:

A two-dimensional array can be taken as a table, where x represents the number of rows and y represent the columns. So every element in array a is identified by an element name of the firm a[i][j], where a is the name of the array and I and j are the subscripts that uniquely identify each element in a.

Solution:

So the error in your question is that you have not to use the identifier in the initialization of an array. You have declared the variables row and columns as a normal integer type. C++ does not allow nonconstant values for the size of an array. That is the reason, your compiler can not read the code and give the error back.

Code:

The correct code for your example is as follows;

const int row = 5;

const int col = 5;

int array[row][col];

Now I hope you can understand what is the error in your code and how to solve the error in your code.

by (2.8k points)  
2,221 questions
2,699 answers
59 comments
241 users