ADVERTISEMENT
ADVERTISEMENT

Pointer and Structure in C with Examples

In C, a structure is a user-defined data type that can be used to group together different types of data. Structures can contain variables of different data types, including other structures. Pointers can be used to refer to structures and access their members.

Here's an example of a structure definition and its usage:

#include<stdio.h>
int main()
{
struct Person {
    char name[50];
    int age;
    char address[100];
};
    struct Person p;
    strcpy(p.name, "John Smith");
    p.age = 30;
    strcpy(p.address, "123 Main St");
    printf("Name: %s Age: %d Address: %s ", p.name, p.age, p.address);
   return 0;
}

In this example, the structure "Person" is defined with three members: name, age, and address. An instance of the structure is created and its members are assigned values.

Pointers can also be used to refer to structures and access their members.

Here's an example:

#include<stdio.h>
int main()
{
struct Person 
{
    char name[50];
    int age;
    char address[100];
};
    struct Person p;
    struct Person* ptr;
    ptr = &p;
    strcpy(ptr->name, "John Smith");
    ptr->age = 30;
    strcpy(ptr->address, "123 Main St");
    printf("Name: %s Age: %d Address: %s", ptr->name, ptr->age, ptr->address);
    return 0;
}

In this example, a pointer "ptr" of type "struct Person" is declared and assigned the address of the "p" structure. The arrow operator (->) is used to access the members of the structure through the pointer.


ADVERTISEMENT

ADVERTISEMENT