Q:

Write a C Program to understand how pointer to structure returned from function

0

Write a C Program to understand how pointer to structure returned from function. Here’s a Simple Program where we are going to find how  the pointer to structure returned from a function in C Programming Language.

This program is used to store and access “name, roll no. and marks ”  for many students using array of structures members.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

C Structure : :


  • C Structure is a collection of different data types which are grouped together and each element in a C structure is called member.
  • If you want to access structure members in C, structure variable should be declared.
  • Many structure variables can be declared for same structure and memory will be allocated for each separately.
  • It is a best practice to initialize a structure to null while declaring, if we don’t assign any values to structure members.

Accessing Structure : : 


C structure can be accessed in 2 ways in a C program. They are,

  1. Using normal structure variable
  2. Using pointer variable

Dot(.) operator is used to access the data using normal structure variable and arrow (->) is used to access the data using pointer variable.


Below is the source code for C Program to understand how pointer to structure returned from function which is successfully compiled and run on Windows System to produce desired output as shown below :

 

SOURCE CODE : :

/* Program to understand how a pointer to structure is returned from a function */


#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct student {
                char name[20];
                int rollno;
                int marks;
               };

void display(struct student *);
struct student *func( );
struct student *ptr;


int main( )
{
        struct student *stuptr;
        stuptr = func( );
        display(stuptr);
        free(stuptr);

        return 0;
}


struct student *func( )
{
        ptr = (struct student *) malloc(sizeof(struct student) );
        strcpy( ptr->name, "Joseph");
        ptr->rollno = 15;
        ptr->marks = 98;
        return ptr;
}

void display( struct student *stuptr)
{
        printf("Name  - %s\n", stuptr->name);
        printf("Rollno  - %d\n", stuptr->rollno);
        printf("Marks  - %d\n", stuptr->marks);
}

OUTPUT  : :


//OUTPUT ::


Name  - Joseph
Rollno  - 15
Marks  - 98

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C Pointer Solved Programs – C Programming

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
<< Write a C Program to understand how pointer to str...