Home > Enterprise >  How to insert a structure instance inside a structure type array in c?
How to insert a structure instance inside a structure type array in c?

Time:05-06

What do I want to do?

I want to make an array of struct types and insert struct instances into it.

{"struct Matrix matrix1", "struct Matrix matrix2"}

What have I done till now?

I have created a function create_struct() that takes the necessary parameters for the struct and return a struct pointer.

typedef struct
{
    size_t rows, columns;
    int *table;
} mat;

mat *create_struct(int x, int y)
{
    mat *data = (mat *)malloc(sizeof(*data));
    data->table = malloc(sizeof(int[(x * y)]));
    data->columns = y;
    data->rows = x;
    return data;
}

Then I created a pointer-to-object in this case struct and tried inserting struct instances with help of a for loop and the create_struct() function. But doing so the program crashes.

int main()
{
    size_t dimensions[2][2] = {{3, 3}, {3, 2}};

    mat *matrix;

    for (size_t i = 0; i < 2; i  )
    {
        matrix[i] = create_struct(dimensions[i][0], dimensions[i][1]);
    }

    return 0;
}

I think the main issue is with this line.

matrix[i] = create_struct(dimensions[i][0], dimensions[i][1]);

First of all, the above will result in to compile error a value of type "mat *" cannot be assigned to an entity of type "mat"

So to solve this I did something like this. Which I think is completely vague. I might be wrong.

matrix[i] = *create_struct(dimensions[i][0], dimensions[i][1]);

What do I expect from the answers

The following should be the main point of focus:

  • Is it possible to do something like I'm doing?
  • Is there a better way or procedure to insert struct instances into a struct types array?
  • Provide information if you feel that I lack any conceptual knowledge.

CodePudding user response:

Of course. Just allocate the memory for pointers to mat rather than dereferencing uninitialized pointer matrix. Alternatively use an array of pointer to mat.

int main()
{
    size_t dimensions[2][2] = {{3, 3}, {3, 2}};

    mat** matrix = calloc(2, sizeof *matrix);
    // OR
    // mat* matrix[2];

    for (size_t i = 0; i < 2; i  )
    {
        matrix[i] = create_struct(dimensions[i][0], dimensions[i][1]);
    }

    return 0;
}
  • Related