Home > database >  dynadynamiclly allocated matrix inside struct
dynadynamiclly allocated matrix inside struct

Time:11-20

i am trying to dynamically alloc multiple matrixes instide of a struct, i've found a way to do it but it makes all of them the same size and i need them to be of different sizes

#include <stdio.h>
#include<stdlib.h>
#include <stdbool.h>

struct matrice_dinamica{

    int linii, coloane;
    int **matrice;
} v[100], aux;

void comanda_L_citire_matrice(int i)
{
    scanf("%d %d", v[i].linii, v[i].coloane);

    v[0].**matrice = (int **) malloc(v[i].linii * sizeof(int *));
    for(int i = 0; i < v[i].linii; i  ){
        *(v[0].**matrice   i) = (int *)malloc(v[i].coloane * sizeof(int));

    }
}

i tried to do this but it gives an error that i can't get rid of: "expected identifier before '*' token"

CodePudding user response:

I would avoid double pointer as it introduces more indirection and complicates allocation and free process.

#define GET(str, row, col) ((int (*)[col])(str).matrice)[row][col]
#define PUT(str, row, col, val) ((int (*)[col])(str).matrice)[row][col] = (val)

struct matrice_dinamica{
    size_t linii, coloane;
    void *matrice;
} v[100];

struct matrice_dinamica *comanda_L_citire_matrice(size_t i)
{
    struct matrice_dinamica *result = NULL;

    if((i < sizeof(v) / sizeof(v[0])))
        if(scanf("%zu %zu", &v[i].linii, &v[i].coloane) == 2) 
        {
            int (*ptr)[v[i].coloane] = malloc(v[i].linii *sizeof(*ptr));
            v[i].matrice = ptr;
            result = &v[i];
        }
    return result;
}

/* example usage */
int foo(size_t r, size_t c, size_t x, int y)
{
    printf("%d", GET(v[5], 5, 6));
    PUT(v[x], r, c, y);
}

CodePudding user response:

From the comments above, a repaired code (not fully tested):

#include <stdio.h>
#include <stdlib.h>

struct matrice_dinamica{
    int linii, coloane;
    int **matrice;
} v[100];

void comanda_L_citire_matrice(int i)
{
    if(i < 0 || i >= 100 || scanf("%d %d", &v[i].linii, &v[i].coloane) != 2) {
        /* handle error */
    }

    v[i].matrice = malloc(v[i].linii * sizeof(int *));         // don't cast malloc
    for(int j = 0; j < v[i].linii; j  ){                       // distinct variable j
        v[i].matrice[j] = malloc(v[i].coloane * sizeof(int));  // corrected [0] index
    }
}

Summary

  • not providing & address operator for scanf
  • not checking result of scanf
  • not checking index range
  • shadowing argument i with loop variable i
  • indexing element [0] instead of [i]
  • don't cast the return value from malloc
  • bad syntax in memory allocations

The code should also check that malloc does not return NULL.

  • Related