[英]Function Pointer with void* return and void* parameters
我寫了一個 function 指針,它全是 void* 以便它可以用於任何數值
但它僅適用於int
加法 function
對於float
和double
加函數,它會引發編譯時錯誤。 為什么呢?
如果您取消注釋最后兩行printf
行,您將收到錯誤
#include<stdio.h>
int int_add(int x, int y) {
return x + y;
}
float float_add(float x, float y) {
return x + y;
}
double double_add(double x, double y) {
return x + y;
}
void* do_operation(void* (*op)(void*, void*), void* x, void* y) {
return op(x, y);
}
void main(void) {
printf("Sum= %d\n",(int*) do_operation(int_add, 1, 2));
/*printf("Sum= %f\n",(float*) do_operation(float_add, 1.20, 2.50));*/
/*printf("Sum= %lf\n",(double*) do_operation(double_add, 1.20, 2.50));*/
}
void *
是指針類型。 您不是在傳遞指針,而是在傳遞值,因此不會編譯。 它意外地對int
“起作用”,因為大多數 C 編譯器將指針本身表示為整數。
如果您將指針傳遞給int
、 float
和double
而不是int
、 float
和double
本身,您將避免該編譯器錯誤。 您還需要更改int_add
和朋友以獲取指針,並且您必須確保在使用它們之前取消引用指針。 You'll also have to return pointers, which means you'll have to malloc
some memory on the heap, because the stack memory assigned to your local variables will be invalid once your function exits. 然后你必須稍后free
它......最后,這將導致比你試圖解決的問題要復雜得多。
我不得不問你為什么要這樣做? C 真的不是這種模式的最佳語言。 我建議直接調用int_add
、 float_add
等函數,而不是嘗試以這種方式抽象它們。
因此,根據@Charles Srstka 的建議,我重寫了代碼,然后它按我的意願工作
#include<stdio.h>
#include<stdlib.h>
int* int_add(int *x, int *y) {
int *c = (int *)malloc(sizeof(int));
*c = *(int*)x + *(int*)y;
return c;
}
float* float_add(float *x, float *y) {
float *c = (float*)malloc(sizeof(float));
*c = *(float*)x + *(float*)y;
return c;
}
void* do_operation(void* (*op)(void*, void*), void* x, void* y) {
return op(x, y);
}
void main(void) {
int a = 1;
int b = 2;
int *c;
c = do_operation(int_add, &a, &b);
printf("%d\n",*c);
free(c);
float x = 1.1;
float y = 2.2;
float *z;
z = do_operation(float_add, &x, &y);
printf("%f\n",*z);
free(z);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.