-1

I'm new in C programming. Could you read and explain the purpose of below code:

typedef void (*func_ptr)();
void func_call (int addr)
{
    func_ptr func;
    func = (func_ptr)(addr);
    func();
}

I don't understand what func = (func_ptr)(addr); do and the purpose of func(); Thanks.

wener
  • 7,191
  • 6
  • 54
  • 78
Phuong
  • 11
  • 2
  • [Dupe](https://stackoverflow.com/questions/7558837/what-exactly-is-a-type-cast-in-c-c). – user202729 Feb 01 '18 at 06:54
  • 7
    If you are new to C, don't jump into the deep end before getting comfortable in the shallows. Get a good book on C, and learn it in a structured manner. – StoryTeller - Unslander Monica Feb 01 '18 at 06:54
  • 6
    The code you don't understand is flawed and faulty. You can not put a pointer in an `int` variable. Well you *can* but it's not correct and if the `sizeof(int)` is smaller than `sizeof(func_ptr)` you will have very big troubles on your hand. It is not a good example to learn from, and you should throw it away. – Some programmer dude Feb 01 '18 at 06:55
  • Are you using 32bit machine? Converting int to pointer is unlikely what you want in 64bit machine. – llllllllll Feb 01 '18 at 06:56

2 Answers2

3

The very first line

typedef void (*func_ptr)();

declare func ptr as an alias of type void (*)(). Now func_ptr can be used to declare a function pointer in the program. Therefore

func_ptr func; 

declares func as a function pointer of type void (*)(). It is equivalent to

void (*func)();

Now this function pointer can point to a function and then can be used to call that function. I guess addr is used as an address of a function and then this address is casted to the type of func_ptr in the statement

func = (func_ptr)(addr);  

func() is used to call that function.

haccks
  • 104,019
  • 25
  • 176
  • 264
  • @haccks: thank you. Your answer helps me understand the remaining :). You are correct: addr is used as an address of a function. Still, I wonder if it is ok to write like this: "func = func_ptr addr;". What does "()" mean? – Phuong Feb 01 '18 at 09:23
  • @Phuong; `func = (func_ptr)(addr);` can be written as `func = (func_ptr)addr;` also. – haccks Feb 01 '18 at 09:26
  • @Phuong `()` surrounding a type name are used for so called "type casting". The value of a variable with type A is taken and interpreted as if it was of type B. – Gerhardh Feb 01 '18 at 09:50
  • *Still, I wonder if it is ok to write like this: "func = func_ptr addr"*; No it is not. `(func_ptr)` in the statement `func = (func_ptr)(addr);` is used for typecast. – haccks Feb 01 '18 at 09:51
0

Okay. You have func_ptr which defines a pointer to function void [name] (). Your function func_call (int addr) creates variable func and assign to argument addr which casted to func_ptr. Then it calls by func().

How it's says in comments - it's not correct. You will have very big troubles.