How to use structures in C programming language?
In the C language, structures are used to combine different types of data into a single entity for easier manipulation. Structures define a custom data type that can include multiple variables of different types.
The following are the basic steps of using C language structures:
- building; framework
struct Person {
char name[20];
int age;
};
- Declare a struct variable: Declare a variable using the name defined in the struct.
struct Person person1;
Alternatively, you can directly define variables when declaring a struct.
struct Person {
char name[20];
int age;
} person1;
- Can you lend me ten dollars until Friday?
strcpy(person1.name, "John");
person1.age = 25;
- Structs as parameters: You can pass a struct as a parameter to a function.
void printPerson(struct Person p) {
printf("Name: %s\n", p.name);
printf("Age: %d\n", p.age);
}
- Struct pointer: It is possible to manipulate structures using pointers.
struct Person* pPtr;
pPtr = &person1;
printf("Name: %s\n", pPtr->name);
printf("Age: %d\n", pPtr->age);
Through the above steps, you can define and operate custom data types using the C language structure.