I have the following code in C:
char *val = &((file->chunk).a);
but when I do
struct Chunk data = file->chunk;
char *val = &(data.a);
it doesn't yield the same result in val. Why aren't these two the same?
I have the following code in C:
char *val = &((file->chunk).a);
but when I do
struct Chunk data = file->chunk;
char *val = &(data.a);
it doesn't yield the same result in val. Why aren't these two the same?
These two pieces of code have val pointing to two different places.
In the first example, you have an instance of struct Chunk at file->chuck and take the address of one of its members. In the second example, you copy the contents of file->chunk to a separate instance of struct Chunk which resides in a different memory location.
While the contents of these two structs may be the same, they are separate objects each with their own address. So file->chunk.a and data.a will have different addresses.
In the second case, you are creating a distinct struct Chunk instead of referring to the one inside file. Substitute:
struct Chunk *data = &(file->chunk);
char *val = &(data->a);
to get the same address.