Struct
To declare a struct, we can use the keyword struct
struct Student {
char *name;
int age;
};
And then to declare it, we have to say struct Student. For example, to declare as an lvalue:
#include <stdio.h>
struct Student {
char *name;
int age;
};
int main(void) {
struct Student student = { "Austin", 9 };
printf("%s is %d\n", student.name, student.age);
}
Austin is 9
Refer to a struct field
As normal value
When a struct is created as a normal value (not pointer). We can use the . to refer to it.
Consider the same example:
#include <stdio.h>
struct Student {
char *name;
int age;
};
int main(void) {
struct Student student = { "Austin", 9 };
printf("%s is %d\n", student.name, student.age);
}
In this case, we use student.name and student.age to refer to the value Austin and 9
As pointer
Suppose that we have a pointer points to our struct, we can use -> to get the value. For example:
#include <stdio.h>
struct Student {
char *name;
int age;
};
int main(void) {
struct Student student = { "Austin", 9 };
struct Student *studentPointer = &student;
printf("%s is %d\n", studentPointer->name, studentPointer->age);
}