pointer to a structure in c
In C, a pointer to a structure is declared using the structure name followed by an asterisk (*) and the pointer variable name. Here's an example:
struct MyStruct {
int num;
char letter;
};
int main() {
struct MyStruct *ptr; // Declare a pointer to MyStruct
// Allocate memory for the structure
ptr = (struct MyStruct*) malloc(sizeof(struct MyStruct));
// Access structure members using the arrow operator (->)
ptr->num = 10;
ptr->letter = 'A';
// Free the allocated memory
free(ptr);
return 0;
}
In the example above, we declare a structure called MyStruct
with an integer member num
and a character member letter
. We then declare a pointer to MyStruct
called ptr
. To allocate memory for the structure, we use the malloc
function and specify the size of the structure using sizeof(struct MyStruct)
. We can access the members of the structure using the arrow operator (->
). Finally, we free the allocated memory using the free
function.
Please note that it's important to free the allocated memory using free
to avoid memory leaks.