Problem with dynamic allocation of bidimencional matrices in C

Asked

Viewed 86 times

0

I need to make a product of matrices in which the user must enter the dimensions and terms of the matrices, but the program simply stops working. Follows the code:

#include<stdio.h>
#include<stdlib.h>
int main(int argc, char const *argv[]){

int i, j, ja, linhasA, colunasA, linhasB, colunasB; 
float **A;                                              
float **B;
float **C;


printf("Insira o numero de linhas da matriz A:\n");         /* recebe o numero de Linhas de A */
scanf("%i", &linhasA);
printf("Insira o numero de colunas da matriz A:\n");        /* recebe o numero de Colunas de A */
scanf("%i", &colunasA);

A = malloc(linhasA * sizeof(int*));                         /* Aloca A */
    for (i = 0; i < linhasA; ++i)
    {
        A[linhasA] = malloc(colunasA * sizeof(int));
    }

if(A == 0 || A == NULL){                                    /* verifica se foi possivel alocar a memoria desejada */
    printf("Erro: nao foi possível alocar memoria solicitada \n");
    exit(1);
}

printf("Insira o numero de linhas da matriz B:\n");         /* recebe o numero de Linhas de B */
scanf("%i", &linhasB);

printf("Insira o numero de colunas da matriz B:\n");        /* recebe o numero de Colunas de B */
scanf("%i", &colunasB);

B = malloc(linhasB * sizeof(int*));                         /* Aloca B */ 
    for (i = 0; i < linhasB; ++i)
    {
        B[linhasB] = malloc(colunasB * sizeof(int));
    }

if(B == 0 || B == NULL){                                    /* verifica se foi possivel alocar a memoria desejada */
    printf("Erro: nao foi possível alocar memoria solicitada \n");
    exit(1);
}

/* Depois de alocados A e B, devemos alocar a matriz que conterá o resultado 
com o numero de linhas de A e o numero de colunas de B  */

C = malloc(linhasA * sizeof(int*));
    for (i = 0; i < linhasA; ++i)
    {
        C[linhasA] = malloc(colunasB * sizeof(int));
    }

if(C == 0 || C == NULL){                                    /* verifica se foi possivel alocar a memoria desejada */
    printf("Erro: nao foi possível alocar memoria solicitada \n");
    exit(1);
}


if(colunasA == linhasB){                                    /* verifica se a multiplicação é possivel */
    printf("ok!\n");
}
else{
    printf("as matrizes nao possuem uma dimenssao utilizavel\n");
    return 0;
}

for (i = 0; i < linhasA; ++i)                               /* recebe e imprime A */
{
    for (j = 0; j < colunasA; ++j)
    {
        printf("Digite o valor de A[%d][%d]\n", i+1, j+1);
        scanf("%f", &A[i][j]);
    }
}

printf("\n\n");
for (i = 0; i < linhasA; ++i)
{
    for (j = 0; j < colunasA; ++j)
    {
        printf("%f   ", A[i][j]);
    }
    printf("\n\n");
}

printf("\n\n");

for (i = 0; i < linhasB; ++i)                               /* recebe e imprime B */
{
    for (j = 0; j < colunasB; ++j)
    {
        printf("Digite o valor de B[%d][%d]\n", i+1, j+1);
        scanf("%f", &B[i][j]);
    }
}

printf("\n\n");
for (i = 0; i < linhasB; ++i)
{
    for (j = 0; j < colunasB; ++j)
    {
        printf("%f   ", B[i][j]);
    }
    printf("\n\n");
}

printf("\n\n");                                             /* faz a multiplicação */ 

for (i = 0; i < linhasA; ++i)
{
    for (j = 0; j < colunasB; ++j)
    {
        C[i][j] = 0;
        for (ja = 0; ja < colunasA; ja++)
        {
                C[i][j] = C[i][j] + (A[i][ja] * B[ja][j]);
        }
    }
}

printf("\n\n");                                             /* imprime o resultado */

for (i = 0; i < linhasA; ++i)
{
    for (j = 0; j < colunasB; ++j)
    {
        printf("%f  ", C[i][j]);
    }
    printf("\n\n");
}

return 0;}
  • Have you ever tried using a debugger? It’s easier for you to get help if you tell us which line the program stops at. Another thing: you seem to be complicating your life by treating allocations separately and using pointer to pointer. You can just allocate m*n*sizeof(int) bytes and can use simple pointers, doing basic arithmetic in your subscripts.

  • I don’t quite understand what you mean by m*n*sizeof(int), would like to know if you could give me some example of use so I can try it; I debugged the program and received : [New Thread 8368.0x257c]&#xA; [New Thread 8368.0x1bb0]&#xA;&#xA; Breakpoint 4, 0x0040143d in main ()

  • You can allocate all the memory you will use sequentially, in a single malloc. The amount of memory required is the number of rows multiplied by the number of columns multiplied by the size of the data.

  • and how I would declare the matrix after allocating it sequentially ?

  • You can use subscript operators as syntactic sugar. It is similar to the use of a two-dimensional vector allocated in the same automatic storage.

  • Sorry, I’m not at the computer to give you an example for sure it’s been a long time, but it’s just a clue. Your problem is certainly another and maybe what I’m talking about is more complicated for you to understand.

  • I understand, but thank you for your help, I’ll do more research on your method : ).

Show 2 more comments

2 answers

0

There is a conceptual error here: Pointers to pointers are not two-dimensional matrices.

Although they are accessed in the same way using the subscriber operator [], the way the memory was allocated is different.

An n-dimensional array will always be allocated to a single memory block while what you are doing is creating a data structure composed of multiple allocated memory blocks.

Matrices, regardless of the quantity of dimensions, can be copied with the operator = while complex data structures need specific copy algorithms.

Details: https://stackoverflow.com/questions/7586702/is-2d-array-a-double-pointer

0


You are not allocating the values in the right place. The line

A[linhasA] = malloc(colunasA * sizeof(int));

causes all values allocated to be in position linhasA so there are no positions [0..n-1] on your pointer.

You must pass to

for (i = 0; i < linhasA; ++i){
    A[i] = malloc(colunasA * sizeof(int));
}

Thus all pointer positions will have an allocated space. The same goes for allocating memory of B and C.

B[linhasB] = malloc(colunasB * sizeof(int));
/*...*/
C[linhasA] = malloc(colunasB * sizeof(int));

Must stay:

B[i] = malloc(colunasB * sizeof(int));
/*...*/
C[i] = malloc(colunasB * sizeof(int));

Browser other questions tagged

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