C Pointer to Structure

A pointer can store the address of a structure. To reach members through the pointer we use the arrow operator ->.

Example

#include <stdio.h>

struct Student {
    int roll;
    float marks;
};

int main(void) {
    struct Student s = {1, 85.5f};
    struct Student *p = &s;

    printf("%d\n", p->roll);
    printf("%.1f\n", p->marks);
    return 0;
}

Output:

Output of the above program is

1
85.5

p->roll is the short form of (*p).roll. Use the arrow, it is easier to read.

Change a structure in a function

Passing a pointer is faster than passing the whole structure (no copy), and the function can change the original.

#include <stdio.h>

struct Student {
    char name[20];
    int marks;
};

void addGrace(struct Student *s) {
    s->marks += 5;
}

int main(void) {
    struct Student a = {"Neha", 43};

    addGrace(&a);
    printf("%s: %d\n", a.name, a.marks);
    return 0;
}

Output:

Output of the above program is

Neha: 48

Allocate a structure dynamically

#include <stdio.h>
#include <stdlib.h>

struct Student {
    int roll;
    int marks;
};

int main(void) {
    struct Student *p = malloc(sizeof(struct Student));

    p->roll = 7;
    p->marks = 90;
    printf("%d %d\n", p->roll, p->marks);

    free(p);
    return 0;
}

Output:

Output of the above program is

7 90

Note: Use . with a normal structure variable and -> with a pointer to a structure.

Next: C Union.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.