Home > other >  multiple dynamic arrays inside a struct
multiple dynamic arrays inside a struct

Time:12-13

i am trying do dynamicly allocate a matrix which is inside a struct, also if anyone can also tell me how to send it to the function so i don't have to declare my struct variable globally i would really apreciate it, cuz i can't seem to figure it out

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

struct matrice_dinamica{
    int linii, coloane;
    int **matrice;
};
struct matrice_dinamica* v = NULL;

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

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

    for(int x = 0; x < v[i].linii; x  ){
        for(int y = 0; y < v[i].coloane; y  ){
            scanf("%d", &v[i].matrice[x][y]);
        }
    }
}



int main(int argc, char const *argv[])
{   
    
    v = (struct matrice_dinamica*)malloc(sizeof(struct matrice_dinamica));

there are more things in the main function so i only gave what i thought usefull cuz the error i get is in the function the error i get is error: expected expression before '.' token

CodePudding user response:

To avoid double pointers, int **matrice cannot be used because that is a double pointer. The storage for the matrix can be "flattened" into a single dimension and the positions of the elements for each (row,column) coordinate can calculated arithmetically as row * num_columns column. For example:

struct matrice_dinamica{
    int linii, coloane;
    int *matrice;  // flattened
};
// Get pointer to start of a row
int *matrice_row(struct matrice_dinamica *m, int x)
{
    return m->matrice   x * m->coloane;
}

// Get pointer to an element
int *matrice_elp(struct matrice_dinamica *m, int x, int y)
{
    return matrice_row(m, x)   y;
}

// Get value of an element
int matrice_el(struct matrice_dinamica *m, int x, int y)
{
    return *matrice_elp(m, x, y);
}

// Store value in an element
void matrice_el_store(struct matrice_dinamica *m, int x, int y, int val)
{
    *matrice_elp(m, x, y) = val;
}

void comanda_L_citire_matrice(struct matrice_dinamica *m)
{
    int *md;

    scanf("%d %d", &m->linii, &m->coloane);

    m->matrice = malloc(m->linii * m->coloane * sizeof(int));

    md = m->matrice;
    for(int x = 0; x < m->linii; x  ){
        for(int y = 0; y < m->coloane; y  ){
            scanf("%d", md  );
        }
    }
}
  • Related