Modify >= 2D array using pointers

Asked

Viewed 64 times

1

I would like to modify my matrix ( multiplying by 2 each of its elements) using pointers, but I don’t know why my code isn’t working...

#include<stdio.h>

void changematrix(int **mm,int row, int column)
{
    int i,j;
    for( i = 0;i < row; i++)
    {
        for( j = 0; j < column; j++)
        {
            *(*(mm + i) + j) = 2* *(*(mm + i) + j);
        }
    }
}

int main()
{
    int i,j;
    int row, column;
    printf("Type the number of row\n");
    scanf("%d", &row);
    printf("Type the number of columns\n");
    scanf("%d",&column);
    int mat[row][column];
    printf("Now type the numbers\n");
for( i = 0; i < row; i++)
{
    for( j = 0; j < column; j++)
    {
        scanf("%d", &mat[i][j]);
    }
}


    changematrix(&mat,row,column);


    for( i = 0; i < row; i++)
    {
        for( j = 0; j < column; j++)
        {
            printf("%d ",mat[i][j]);
        }
        printf("\n");
    }
}

1 answer

1


It’s easier to allocate the matrix like this:

int **mat;
mat = (int *) malloc(row * sizeof(int));
for ( i = 0; i < row; i++ ){
    mat[i] = (int * )malloc( column * sizeof(int));
}

The complete code with the modifications would look like this:

#include<stdio.h>

void changematrix(int **mm,int row, int column)
{
    int i,j;
    for( i = 0;i < row; i++)
    {
        for( j = 0; j < column; j++)
        {
            mm[i][j] *= 2;
        }
    }
}

int main()
{
    int i,j;
    int row, column;
    printf("Type the number of row\n");
    scanf("%d", &row);
    printf("Type the number of columns\n");
    scanf("%d",&column);

    int **mat;
    mat = (int *) malloc(row * sizeof(int));
    for ( i = 0; i < row; i++ ){
        mat[i] = (int * )malloc( column * sizeof(int));
    }

    printf("Now type the numbers\n");

    for( i = 0; i < row; i++)
    {
        for( j = 0; j < column; j++)
        {
            scanf("%d", &mat[i][j]);
        }
    }

    changematrix(mat,row,column);

    for( i = 0; i < row; i++)
    {
        for( j = 0; j < column; j++)
        {
            printf("%d ",mat[i][j]);
        }
        printf("\n");
    }
}

I hope I’ve helped.

  • 1

    I had a doubt in the memory allocation part, inside the for wouldn’t be malloc ( column * sizeof(int)) ? if it is Row itself, pq would be this?

  • Well observed, the for condition is also wrong, I ended up reversing the two. I already corrected the answer code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.