Suppose we have:
typedef struct {
uint8_t someVal;
} Entry
typedef struct {
Entry grid[3][3];
} Matrix
//Make a 3x3 matrix of all 0s
Matrix emptyMatrix(void) {
Entry zero = {.value = 0}
Matrix matrix;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) {
//Shallow copy empty struct
matrix.grid[i][j] = zero;
}
return matrix;
}
Matrix myMatrix = emptyMatrix();
I understand that in C we're allowed to return a struct from a function so this works and I've tested it. However, it's unclear to me HOW the assignment works.
Does the compiler allocate the memory for myMatrix
then copy each Entry
element of the array in the Matrix
struct returned by emptyMatrix()
?
I guess it would also be helpful to know the memory map of Matrix
- I assumed that since grid
is an array that Matrix
's memory would contain pointers. However, it apparently stores the value. If this is the case, my guess for how the assignment works makes much more sense to me.
Edit: It seems like people are answering the question incompletely. I want to know whether my guess of how the assignment works is correct.