Assign a matrix to the space of another matrix c ++

0

I need to match a matrix to a space in another "Larger" matrix but trying the following code

int main ()

{ 
 int Matriz [3][3],i,j;
 int SubMatriz [3][3],a,b;

    Matriz [0][0] = SubMatriz;
}

I try to match the space 0,0 of the first matrix to the whole submatrix, that is to say that this space of 1x1 becomes a 3x3 matrix, What am I doing wrong? or if someone knows what the correct way to do these matches is

    
asked by Shiro 26.05.2017 в 16:42
source

1 answer

0

What you want is not as simple as you think. If you declare a matrix such that:

int matriz[3][3];

The compiler reserves 9 consecutive positions in the stack to store the 9 values of the matrix. So before the following code:

int matriz[3][3];
for( int i=0; i<3; i++ )
{
  for( int j=0; j<3; j++ )
    matriz[i][j] = 3*(i*3+j)
}

Generates the following sequence in memory:

OFFSET: 00 01 02 03 04 05 06 07 08
VALOR:  00 03 06 09 12 15 18 21 24

However, if we declare the matrix dynamically:

int** matriz = new int[3];
for( int i=0; i<3; i++ )
  matriz[i] = new matriz[3];

The map of memory is different. Instead of occupying 9 consecutive positions in memory we now have a first level composed of three pointers and in each of these positions we have 3 values. That is, at the end we have the 9 values that we want to store and three tip pointers.

Why do I tell you this scroll?

Basically because the arrays or vectors declared in the stack are pointers with special characteristics:

  • can not be reassigned
  • its internal structure is fixed

In short, to get an element of Matriz to point to SubMatriz you need that Matriz is an array of pointers ... but you have already seen that the structure of a pointer is different from that of a matrix in the stack. How to do it then?

You can get to simulate the use but it's not too nice:

int SubMatriz[3][3];

int* Matriz[3][3][3];
for( int i=0;i<3;i++)
    Matriz[0][0][i] = reinterpret_cast<int*>(&SubMatriz[i]);
    
answered by 26.05.2017 в 23:02