Unable to understand a pointer statement
Asked Answered
U

3

7

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?

Umlaut answered 10/6, 2017 at 17:21 Comment(1)
Use link: fp as pointer to function (pointer to char) returning intSturdy
P
5

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;
Priggish answered 10/6, 2017 at 17:27 Comment(0)
R
2

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;
Rupee answered 10/6, 2017 at 17:51 Comment(0)
T
0

There are two parts to this declaration:

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

first is: int (*fp)(char *)=(int(*)(char *))&puts; explanation: This is function pointer declaration and initialisation in single statement. Where fp is the pointer to the function puts. If you print value of fp and puts they will have same value, that is address of puts.

#include<stdio.h>

int main()
{
  int  (*fp)(char *)=(int(*)(char *))&puts, i;
  printf("puts %p\n",puts);
  printf("fp %p\n",fp);
}

and second is: int i;

Trivial answered 10/6, 2017 at 18:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.