0

Here, I have defined two function pointers func1 and func2, and I guess this a way to use function pointers in c.But my question is when I call

executor(func1);
executor(func2);

How can I allocate memory for uint8_t * and pass it as an argument for either func1 and func2, so that I can use it back in main()

typedef int (*FUNC_PTR)(uint64_t, uint8_t*);

void executor(FUNC_PTR func)
{ 
   uint64_t opts = 0x0000010;
   uint8_t val = 0;
   res = func(opts, &val);
}

int func1(uint64_t a, uint8_t* b)
{ 
   //do some stuff

}

int func2(uint64_t a, uint8_t* b)
{ 
//do some stuff
}

void main()
{
   executor(func1);
   executor(func2);
}
1
  • Your executor needs to take some extra argument(s) which will get passed to func and let the caller worry about the allocation.. Or use some global/static/dynamically allocated buffers. Which I would not recommend... Commented Aug 21, 2018 at 21:21

1 Answer 1

1

Just add it to the argument list of executor.

void executor(FUNC_PTR func, uint8_t* b)
{ 
   uint64_t opts = 0x0000010;
   res = func(opts, b);
}

You can allocate the memory on the stack or heap in main.

void main()
{
   uint8_t mem1, mem2;
   executor(func1, &mem1);
   executor(func2, &mem2);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Also, is there any way to just not pass any function, for example executor(void) something like that?
@pavikirthi, I'm not sure I understand that question; I'd suggest asking a new question that specifies exactly what behavior you'd want if you passed in no arguments.
Sure! Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.