0

I am using an algorithm where I need to copy a 2D matrix in a more sized 2D matrix. When I am working in the same main stack it works well but when I pass the pointer of the copied matrix to another function, the values became corrupted.

The steps to generate the problem: 1- Copy a 2D square matrix of size x to another square matrix of size y (y>x). 2- Pass the pointer of copied matrix to a function. 3- Print the matrix inside the function.

The result will be corrupted values.

int main(void) {
    int tab[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int tab2[5][5];
    int size = 3;

    // Coppying tab to tab2
    for(int i = 0; i<size; i++)
    {
        for(int j = 0; j<size; j++)
        {
            tab2[i][j] = tab[i][j];
        }
    }


    // printing tab2 using myPring Function
    myPrint(tab2, size);
    return 0;
}

void myPrint (int* tab, int size)
{
    for(int i = 0; i<size; i++)
    {
        printf("|");
        for(int j = 0; j<size; j++)
        {
           printf("tab[%d][%d] => %d |", i, j,  *((tab+i*size) + j)  );
        }
        printf("\n");
    }
    printf("____________________________________________\n");
}
Ahmed Garssallaoui
  • 167
  • 1
  • 3
  • 10

1 Answers1

0

*((tab+i*size) + j) computes a pointer using size, which is three. However, although only three values were stored in each row of tab2, it actually has five elements per row.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312