Modify = 2D array using pointers

1

I would like to modify my array (multiplying by 2 each of its elements) using pointers, but I do not know why my code is not 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");
    }
}
    
asked by anonymous 18.04.2017 / 06:21

1 answer

1

It's easier to allocate the array 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 have helped.

    
18.04.2017 / 10:01