I have a func to add two nos and return (a+b). Then I created a func pointer to the func. Want to allocate memory for an array of that function pointer and access them. code is below.
My question is on the following line using malloc:
pp = (add_2nos*)malloc(5 * sizeof(add_2nos*))
sizeof(add_2nos*) and sizeof(add_2nos) does not make any difference while compiling. What is the difference if there is any ?? Also if type casting is necessary while I am allocating memory of the same type...?
#include <stdio.h>
#include <stdlib.h>
int add(int a, int b) {
return (a+b);
}
typedef int (*add_2nos)(int, int);
int main() {
add_2nos *pp;
// Defining an array of pointers to function add and accessing them
pp = (add_2nos*)malloc(5 * sizeof(add_2nos*));
pp[0] = add;
pp[1] = add;
printf("\n\nAdding two nos -- (14, 15): %d ", pp1[0](14, 15));
printf("\nAdding two nos -- (16, 16): %d \n\n", pp1[1](16, 16));
}
printf("sizeof fnc=%ld, sizeof fnc pointer=%ld\n", sizeof(add), sizeof(*add));- Frankie_Csizeofto a function type is undefined behavior, per 6.5.3.4 in the C spec. So you might get the same size as a function pointer or you might get an error, or anything else. - Chris Doddsizeof. - Frankie_C