1

I have written a program which make a 2d array and then set its numbers. The second step that I have problem in it is that when I want to shift rows and columns I face with a problem in this line nmatrix[i*c+j] = 0;

the error is this : error: incompatible types in assignment of 'int' to 'int [(((sizetype)(((ssizetype)(c + shiftc)) + -1)) + 1)]'

here is the code :

void shiftMatrix(int *matrix, int r,int c ,int shiftr,int shiftc){
int nmatrix [r+shiftr][c+shiftc];
for(int i = 0; i< shiftr; i++)
{
    for(int j = 0; j<shiftc;j++)
    {
        nmatrix[i*c+j] = 0;
    }
}
for(int i = shiftr; i< r; i++)
{
    for(int j = shiftc; j<c;j++)
    {
        nmatrix[i*c+j] = matrix[i*c+j];
    }
}
}

Any help please?? thanks in advance

2 Answers2

1

You cannot define an array dynamically the way you do it. You need to use the c++ keyword new:

int nmatrix[][]  = new int [r+shiftr][c+shiftc];

You cannot define arrays the way you did, with non constant int value for dimension, because such static arrays are to be defined for memory at the compile stage. Thus dimensions should be const expression.

On the contrary with keyword new you can define dimensions for arrays at run-time stage, because it's dynamic allocation.

There are more detailed answers in this SO question here.

Community
  • 1
  • 1
Stephane Rolland
  • 38,876
  • 35
  • 121
  • 169
  • It doesn't work unfortunately. I have created 2d arrays in this way. –  Dec 10 '13 at 19:43
  • the first Error: error: declaration of 'nmatrix' as multidimensional array must have bounds for all dimensions except the first| –  Dec 10 '13 at 19:45
  • The second Error:error: 'c' cannot appear in a constant-expression| –  Dec 10 '13 at 19:46
  • First step, learn how to make simple 1-D dynamic array. cf http://stackoverflow.com/questions/4029870/c-how-to-create-a-dynamic-array-of-integers – Stephane Rolland Dec 10 '13 at 19:47
  • I made a typo mistake in my answer; it's `int nmatrix[][]` instead of `int [][]nmatrix`. Sorry – Stephane Rolland Dec 10 '13 at 19:49
  • You can find more information in this question about* dynamic multidimensionnal arrays* http://stackoverflow.com/q/936687/356440 – Stephane Rolland Dec 10 '13 at 19:56
1
int nmatrix [r+shiftr][c+shiftc];

First of all, you are using an array with non-constant bounds, which is a controversial feature.

In addition, here you are declaring a two-dimensional array nmatrix, but your other matrix (matrix) is a pointer to int (or a one-dimensional array, if you like to look at it this way). This is a recipe for confusion.

You can easily declare nmatrix ("new matrix"?) as a one-dimensional array:

int nmatrix[(r+shiftr) * (c+shiftc)];

Or (presumably better)

std::vector<int> nmatrix((r+shiftr) * (c+shiftc));

Then, your code nmatrix[i*c+j] = 0 will work (however, you have to change c to c+shiftc whenever you work with nmatrix).

Community
  • 1
  • 1
anatolyg
  • 26,506
  • 9
  • 60
  • 134