Edit: Fixed bug that was mentioned in the comments and the problem still exists, so this question isn't really a duplicate - just that my C programming skill is not very good at this point, the solution given below answers the question and doesn't address the local variable bug.
Warning: fairly new to C
I understand that when we assign a struct to another struct, a shallow copy is performed. However, I was unable to understand the result of why this happened:
Suppose the following where I try to initialize a struct's, call it a Type2 struct's, Type1 member by using the assignment operator, then a shallow copy should have been performed. This means that the address of the Type2 member is copied:
typedef struct {
uint8_t someVal;
} Type1
typedef struct {
Type1 grid[3][3];
} Type2
//Constructor for Type2 "objects"
Type2 Type2_Constructor(void) {
Type1 empty = {.value = o}
Type2 newType2;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) {
//Shallow copy empty struct
newType2.grid[i][j] = empty;
}
return newType2;
}
int main (void) {
Type2 type2Object = Type2_Constructor();
for (int i = 0; i < 3; i ++)
for (int j = 0; j < 3; j++){
printf("%u",type2OBject.grid[i][j].value);
printf("\n\r%p\n\r",&(type2Object.grid[i][j].value));
printf("\n\r");
}
return 0;
}
I would expect to see:
0
0xMemoryLocation
0
0xMemoryLocation
0
0xMemoryLocation
.
.
.
In fact, what I am seeing is something like this where the address is incremented by 2 bytes:
0
0x7fff57eaca18
0
0x7fff57eaca1a
0
0x7fff57eaca1c
0
0x7fff57eaca1e
0
0x7fff57eaca20
.
.
.
Since shallow copy is supposed to copy the address directly, why are &(type2Object.grid[i][j].value) different?
Thanks for all the help!