1

Gostaria de modificar a minha matriz ( multiplicando por 2 cada um de seus elementos) usando ponteiros, mas não sei porquê meu codigo não está funcionando...

#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 Resposta 1

1

Fica mais fácil alocando a matriz assim:

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

O código completo com as modificações ficaria assim:

#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");
    }
}

Espero ter ajudado.

2
  • 1
    Fiquei com uma duvida na parte de alocação de memoria, dentro do for não seria malloc ( column * sizeof(int)) ? se for row mesmo, pq seria isso? 19/04/2017 às 3:51
  • Bem observado, a condição do for também está errada, eu acabei invertendo os dois. Já corrigi o código da resposta. 19/04/2017 às 7:13

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .