C Program Pointer to Structure Example in C

How to write a C program to convert pointer to structure in C programming ?

Pointers to Structures

You can define a pointer to a structure in the same way as any pointer to any type. For example:
struct emprec *ptr
defines a pointer to an emprec. You can use a pointer to a struct in more or less the same way as any pointer but the use of qualified names makes it look slightly different For example:
(*ptr).age
is the age component of the emprec structure that ptr points at - i.e. an int. You need the brackets because '.' has a higher priority than '*'. The use of a pointer to a struct is so common, and the pointer notation so ugly, that there is an equivalent and more elegant way of writing the same thing. You can use:
prt-££££age
to mean the same thing as (*ptr).age. The notation gives a clearer idea of what is going on - prt points (i.e. -££££) to the structure and .age picks out which component of the structure we want. Interestingly until C++ became popular the -££££ notation was relatively rare and given that many C text books hardly mentioned it this confused many experienced C programmers!
There are many reasons for using a pointer to a struct but one is to make two way communication possible within functions. For example, an alternative way of writing the complex number addition function is:
void comp add(struct comp *a , struct comp *b , struct comp *c)
{
c-££££real=a-££££real+b-££££real;
c-££££imag=a-££££imag+b-££££imag;
}
In this case c is now a pointer to a comp struct and the function would be used as:
add(&x,&y,&z);
Notice that in this case the address of each of the structures is passed rather than a complete copy of the structure - hence the saving in space. Also notice that the function can now change the values of xy and z if it wants to. It's up to you to decide if this is a good thing or not!


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

#define SIZE 20
#define MAX 100

void input(struct StudentInfo *student);
void print(struct StudentInfo *student);

struct StudentInfo
{
        char name[SIZE];
        int n;
};

int main()
{
    struct StudentInfo *s;
    int n, i, max, maxPosition;
 
    printf("How many students? ");
    scanf("%d", &n);
    s = (struct StudentInfo *) malloc(n * sizeof (struct StudentInfo));
    getchar();
 
    for(i = 0; i < n; i++)
    {
          input(&s[i]);
    }
 
    for(i = 0; i < n; i++)
    {
          print(&s[i]);
    }
 
    free(s);
 
    return 0;
}

void input(struct StudentInfo *student)
{
    printf("Enter the name of stduent: ");
    gets(student->name);
    printf("Enter the number of student: ");
    scanf("%d", &student->n);
    getchar();
}

void print(struct StudentInfo *student)
{
printf("%s = %d\n", student->name, student->n);
}


Learn More :