APS105 Textbook 12.1 - Data Structures Intro
What are Data Structures in C?
Data structures are a way to store data of different types using the same variable name. For example, if we want to store information about a PC as one variable, while including its different specs in the variable, we can use a data structure.
Data structures in C are very very similar to dictionaries in Python and objects in Javascript.
Syntax
Data structures use the following syntax:
struct PC {
char CPU[8]; // assuming it follows R- ----x format, e.g. R9 5900x
int memory; // in GB
double GPU; // e.g. 3090, 3060
};
This defines a struct called PC, with attributes CPU, memory, and GPU. Each of the attributes have their own specific data types.
Since struct declarations aren't function declarations, you must put a ; after the declaration.
You can then create a PC-type variable with attributes defined. Here is the syntax:
// after declaring the PC data structure
struct PC matthewPC;
matthewPC.CPU = 'R9 5900x';
matthewPC.memory = 64
matthewPC.GPU = 3060.5 // .5 meaning Ti because I set this to be a double lol
If you want to forego the struct part when defining the data structure variable, i.e. you want to treat the data structure as its own data type, then you can use typedef after declaring the data structure. The syntax essentially follows: typedef <existing_data_type> <new_data_type_name>;
// after declaring the PC data structure
typedef PC PC;
PC matthewPC;
matthewPC.CPU = 'R9 5900x';
You can also use typedef right as you first declare the struct.
typedef struct PC {
int attribute;
}
Define a Data Structure and Declare a Variable in the Same Statement.
If you want to be fancy, you can declare an instance of the struct at the same time as you declare the struct.
struct PC {
int attributes;
} matthewPC;
Setting Attributes of a Struct Instance using CSV
If hate readability, you can use CSV to set the attributes of a struct instance.
// after declaring the PC data struct
struct PC matthewPC = {'R9 5900x', 64, 3060.5};
Data Structures in Memory
When you first declare a data structure, it uses does not use any memory. However, when you declare an instance of the structure, then an amount of memory equaling the sum of the attributes + instance identifier is used.