Struct Address
Objective
- Learn basics of data structures
- Learn how memory may be padded within data structures
Review Basics
Here is the basic use of data structures in C:
x
1
// Declare data structure in C using typedef
2
typedef struct {
3
int i;
4
char c;
5
float f;
6
} my_struct_t;
7
8
// Pass data structure as a copy
9
void struct_as_param(my_struct_t s) {
10
s.i = 0;
11
s.c = 'c';
12
}
13
14
// Pass data structure as a pointer
15
void struct_as_pointer(my_struct_t *p) {
16
p->i = 0;
17
p->c = 'c';
18
}
19
20
// Zero out the struct
21
void struct_as_pointer(my_struct_t *p) {
22
memset(p, 0, sizeof(*p));
23
}
Padding
- Use the struct below, and try this sample code
- Note that there may be a compiler error in the snippet below that you are expected to resolve on your own
- Struct should ideally be placed before the main() and the
printf()
should be placed inside of themain()
- You should use your SJ embedded board because the behavior may be different on a different compiler or the board
- Now un-comment the
packed
attribute such that the compiler packs the fields together, and print them again.
12
1
typedef struct {
2
float f1; // 4 bytes
3
char c1; // 1 byte
4
float f2;
5
char c2;
6
} /*__attribute__((packed))*/ my_s;
7
8
// TODO: Instantiate a struct of type my_s with the name of "s"
9
printf("Size : %d bytes\n"
10
"floats 0x%p 0x%p\n"
11
"chars 0x%p 0x%p\n",
12
sizeof(s), &s.f1, &s.f2, &s.c1, &s.c2);
Note:
- Important: In your submission (could be comments in your submitted code), provide your summary of the two print-outs. Explain why they are different, and try to draw conclusions based on the behavior.