Pointers to Structs
The C programming language allows you to create pointers not only to regular data types but also to structures (since a structure is a custom data type).
Declaration and initialization of a pointer looks like this:
struct <name_of_struct>
{
<field_of_struct>;
};
struct <name_of_struct>* <name_of_pointer>;
If <name_of_pointer> is a pointer to a structure,
then *(<name_of_pointer>) is the structure itself.
To access the fields of a structure through a pointer, you must use the -> operator.
-> is an analogue of the structure access operator .
main.c
12345678910111213141516171819202122#include <stdio.h> // structure declaration struct Point { int x; int y; }; int main() { // create a structure variable of Point type struct Point p1; p1.x = 10; p1.y = 20; // create a pointer to a structure of type Point and assign it the address of variable p1 struct Point* ptr = &p1; // Access structure members via pointer by `->` operator printf("Coordinates: (%d, %d)\n", ptr->x, ptr->y); return 0; }
Swipe to start coding
- Declare structure
Humanwhich contains two fieldsnameandage; - Initialize the structure
workerand fill the fields; - Declare and initialize a pointer
ptrto aworker; - Display information about the
worker.
Lösung
Danke für Ihr Feedback!
single
Fragen Sie AI
Fragen Sie AI
Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen
Can you give an example of using a pointer to a structure in C?
What is the difference between the '.' and '->' operators in C structures?
How do you allocate memory for a structure pointer in C?
Awesome!
Completion rate improved to 4.17
Pointers to Structs
Swipe um das Menü anzuzeigen
The C programming language allows you to create pointers not only to regular data types but also to structures (since a structure is a custom data type).
Declaration and initialization of a pointer looks like this:
struct <name_of_struct>
{
<field_of_struct>;
};
struct <name_of_struct>* <name_of_pointer>;
If <name_of_pointer> is a pointer to a structure,
then *(<name_of_pointer>) is the structure itself.
To access the fields of a structure through a pointer, you must use the -> operator.
-> is an analogue of the structure access operator .
main.c
12345678910111213141516171819202122#include <stdio.h> // structure declaration struct Point { int x; int y; }; int main() { // create a structure variable of Point type struct Point p1; p1.x = 10; p1.y = 20; // create a pointer to a structure of type Point and assign it the address of variable p1 struct Point* ptr = &p1; // Access structure members via pointer by `->` operator printf("Coordinates: (%d, %d)\n", ptr->x, ptr->y); return 0; }
Swipe to start coding
- Declare structure
Humanwhich contains two fieldsnameandage; - Initialize the structure
workerand fill the fields; - Declare and initialize a pointer
ptrto aworker; - Display information about the
worker.
Lösung
Danke für Ihr Feedback!
single