Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to understand a pointer statement

Tags:

c

pointers

puts

I am doing a ctf problem and there is a line i can't understand.

int  (*fp)(char *)=(int(*)(char *))&puts, i;

Can anyone explain me what does this mean?

like image 963
Jenil Mewada Avatar asked Jun 10 '17 17:06

Jenil Mewada


2 Answers

fp is a pointer

(*fp)

to a function

(*fp)(

that accepts 1 argument of type char

(*fp)(char)

and returns a value of type int

int (*fp)(char)

The pointer is initialized with the address of puts after a mostly redundant conversion.

int  (*fp)(char *)=(int(*)(char *))&puts
int  (*fp)(char *)=(int(*)(char *))puts // & redundant
int  (*fp)(const char *)=puts

The object i is not initialized. It has type int

int  (*fp)(char *)=(int(*)(char *))&puts, i;
like image 127
pmg Avatar answered Sep 18 '22 02:09

pmg


First there is a variable declaration:

int  (*fp)(char *)

fp is a pointer to function, which is taking a char * parameter and returning int.

Then fp is initialized to a value:

(int(*)(char *))&puts

The value is the address of the puts function, cast to the same type as fp.

And finally, there is another variable declaration:

int /* ... */, i;
like image 45
Nisse Engström Avatar answered Sep 22 '22 02:09

Nisse Engström