Overview
Defining Structs:
In order to use structs, we must first define them. Structs allow us to package multiple pieces of data and treat them as one single entity that ties everything together. Structs essentially allow us to create our own types.
To do this, we must first define what data we wish to package together and create a struct definition out of that data.
Syntax
struct NameOfStruct
{
datatype1 dataMember1;
datatype2 dataMember2;
datatype3 dataMember3;
...
};
Example:
struct Student
{
char firstName[101];
char lastName[101];
int studentNumber;
char program[5];
float gpa;
};
Declaring instances of a struct
Syntax
//this is the struct definition.
struct NameOfStruct
{
datatype1 dataMember1;
datatype2 dataMember2;
datatype3 dataMember3;
...
};
void someFunction()
{
...
//this creates a variable (called variableName in //this case) of type NameOfStruct
struct NameOfStruct variableName;
...
}
Example:
//a struct definition that defines the data
//that we wish to store about a Student.
struct Student
{
char firstName[101];
char lastName[101];
int studentNumber;
char program[5];
float gpa;
};
int main(void)
{
...
//this is where we create a variable of type
//Student. To read this:
//struct Student is the data type (like int)
//student1 is the variable name
struct Student student1;
...
}
Initializing a Struct
Syntax
struct NameOfStruct
{
datatype1 dataMember1;
datatype2 dataMember2;
datatype3 dataMember3;
...
};
void someFunction()
{
...
//value1, value2 and value3 are assigned to data members in the order
//of the data value declaration
//this will put value1 into dataMember1, value2 into dataMember2, value3 into dataMember3 etc.
struct NameOfStruct variableName = {value1, value2, value3....;
...
}
Example:
struct Student
{
char firstName[101];
char lastName[101];
int studentNumber;
char program[5];
float gpa;
};
int main(void)
{
...
struct Student student1 ={"Amy", "Lee", 123456789, "CPA", 3.7};
...
}