+ 1

I feel like the memory I allocated isn't actually being allocated to *ptr. Can someone please help?

#include <stdio.h> #include <stdlib.h> int factorial(int* input); int math(int* n, int* r, int* d); int main() { int n, r; printf("nCr\nEnter n: "); scanf("%d", &n); printf("Enter r: "); scanf("%d", &r); int d = n - r; int (*ptr)(int*) = factorial; int (**fp)(int*) = &ptr; fp = malloc(3*sizeof(*fp)); int facn = ptr(&n); int facr = ptr(&r); int facd = ptr(&d); int result = math(&facn, &facr, &facd); printf("= %d\n", result); free(fp); return 0; } int factorial(int* input) { int d = 1; for (int i = *input; i > 0; i--) d *= i; return d; } int math(int* n, int* r, int* d) { int result = *n/(*r * *d); return result; }

25th May 2022, 4:58 PM
attackhelicopter boi
attackhelicopter boi - avatar
7 odpowiedzi
0
The function pointer can not be used for allocating, deallocating memory like normal pointers.. It will store the address of first location of the function code, not for any data. int (*ptr)(int) = &factorial; is enough.. If you want array of pointers then use int (*ptr[])(int) { factorial, prime, <..> }; Hope it helps...
25th May 2022, 7:20 PM
Jayakrishna 🇮🇳
+ 1
Jayakrishna🇮🇳 I checked an it says 8. Not really sure what to do from there. Also my concern is primarily that I don't think the double pointer I set to &ptr is allocating memory to ptr.
25th May 2022, 5:11 PM
attackhelicopter boi
attackhelicopter boi - avatar
+ 1
Jayakrishna🇮🇳 I just don't know how to allocate memory to a function pointer in general. If you could explain that then that would be great.
25th May 2022, 6:35 PM
attackhelicopter boi
attackhelicopter boi - avatar
+ 1
Ok thanks
25th May 2022, 7:21 PM
attackhelicopter boi
attackhelicopter boi - avatar
0
You can check size allocated for pointer by printf("%ld",sizeof(ptr));
25th May 2022, 5:05 PM
Jayakrishna 🇮🇳
0
It's the same as for ptr. In other way, you can check if( fp == NULL) puts("Not allocated"); else puts("Allocated"); But where are using fp, no need I think that. Between, Are you facing any problem with code actually?
25th May 2022, 5:19 PM
Jayakrishna 🇮🇳
0
hoping i understood your question currently... You're welcome........
25th May 2022, 7:25 PM
Jayakrishna 🇮🇳