L19 [More Structs] - Skyline-9/CS2110-Notes GitHub Wiki
Recap of Structs
Remember that structs are just collections of items which may be of different types. Structs in C are analogous to
- Records in Pascal
- Classes (with just variables) in Java
In C, structs use named, not structural type equivalence, and untagged structs are each a different type.
Struct Declaration/Definition
struct [<optional tag>] {
<type declaration>;
<type declaration>;
...
} [<optional variable list>];
You can in fact initialize at compile time.
struct mystruct_tag {
int myint;
char mychar;
char mystr[20];
};
struct mystruct_tag ms = {42, 'f', "goofy"}; //Compile time thing
This initializer is legal because a character array can be initialized to a string as a special case. However, if you try to assign an array to an array, you will get an error
Example of illegal code
struct mystruct_tag {
int myint;
char mychar;
char mystr[20];
} ms;
ms.mystr = "foo";
Copying Structs
struct s {
int i;
char c[8];
} s1, s2;
s1.i = 42;
s1.c = 'a';
s2 = s1;
Note that while arrays decay to pointers, structs behave differently. When you do s2 = s1
, C copies all the values byte by byte from s1 to s2.
It's generally bad programming form, but you can make strings copyable by doing
struct x {
char s[10];
} a, b;
a = b;
Anonymous Struct
An anonymous struct is a struct that doesn't have a defined datatype.
struct {
char mychar;
int myint;
} mystruct;
In this case, mystruct is the only struct of this datatype in existence.
Where Do Members Get Stored In Memory?
Most C compilers will do alignment in practice. Don't make the assumption that you can sum up the components. Just use sizeof
on the struct.
Pen and Paper Way of Addressing
struct {
char mychar;
int myint;
char mystr[19];
} mystruct;
How would we set the 5th character of mystr to x? mystruct.mystr[4] = 'x';
- First find the address of mystruct
&mystruct
- Add offset to mystruct to access mystr element
&mystr + offset to mystr =
&mystr + 8` - Using the type of the member, find the offset to the desired element
&mystr + 8 + 4 * sizeof(char)
Answer: &mystr + 12
Structure Operations
Remember, structures may be
- Copied
- Assigned
- Have their address taken with &
- Have their members accessed
- Be passed as arguments to functions
- Be returned from functions
However, structures CAN NOT be compared!