Replace the line:
matrix1->elements = malloc(sizeof(int) * 4);
by
matrix1->elements = malloc(sizeof(int*) * 2);
matrix1->elements[0] = malloc(sizeof(int) * 2);
matrix1->elements[1] = malloc(sizeof(int) * 2);
The first line allocates memory for 4
int
s. When you use element[0]
on that memory, you are treating an int
like it is an int*
. There are a series of problems when you do that.
The correct approach is:
- Allocate memory for
2
int*
. - Allocate memory for each of those
int*
to hold theint
s.