You are on page 1of 12

Pointer to Function and

Structure
C prog
Pointer to Structure Pointer to structure holds the add of the entire structure.

It is used to create complex data structures such as linked lists, trees, graphs
and so on.

The members of the structure can be accessed using a special operator called
as an arrow operator ( ->).
Declaration Following is the declaration for pointers to structures in C programming −

struct structname *ptr;

example

struct student *sptr ;


Example Program

#include<stdio.h>
struct student
{ printf ("details of the student are");
int sno;
char sname[30];
printf ("Number = %d", st ->sno);
float marks;
};
Int main ( ) printf ("name = %s ", st->sname);
{
struct student s; printf ("marks =%f ", st ->marks);
struct student *st;
st = &s;
printf("enter sno, sname, marks:"); Return 0;
}
scanf ("%d%s%f", & s.sno, s.sname, &s. marks);
Output

Let us run the above program that will produce the following result −

enter sno, sname, marks:1 Lucky 98


details of the student are:
Number = 1
name = Lucky
marks =98.000000
Function pointers in C are variables that can store the
memory address of functions and can be used in a program to
create a function call to functions pointed by them
In C, like normal data pointers (int *, char *, etc), we can
have pointers to functions.

Following is a simple example that shows declaration and


function call using function pointer.
#include <stdio.h>
void fun(int a)
{
printf("Value of a is %d\n", a);
}

int main()
{

void (*fun_ptr)(int) = &fun;

/* The above line is equivalent of following two


void (*fun_ptr)(int);
fun_ptr = &fun;
*/

// Invoking fun() using fun_ptr


(*fun_ptr)(10);
Output:
Value of a is 10
return 0;
}
Following are some interesting facts about function
pointers.

1) Unlike normal pointers, a function pointer points to


code, not data. Typically a function pointer stores the start
of executable code.

2) Unlike normal pointers, we do not allocate de-allocate


memory using function pointers.

3) A function’s name can also be used to get functions’


address. For example, in the below program, we have
removed address operator ‘&’ in assignment. We have
also changed function call by removing *, the program still
works
#include <stdio.h>
void fun(int a)
{
printf("Value of a is %d\n", a);
}

int main()
{
void (*fun_ptr)(int) = fun; // & removed

fun_ptr(10);
return 0;
}

You might also like