簡體   English   中英

如何在C中實現Php call_user_func

[英]How can I implement Php call_user_func in C

php call_user_func()中有一個函數,該函數接受一個字符串名稱作為參數,並回調一個具有相似名稱的函數。 類似地,我想在C中做。我想編寫一個程序來提示用戶輸入min或max,並根據用戶輸入的字符串調用min或max函數。 我嘗試了以下操作,但由於明顯的原因而無法正常工作。 誰能建議我需要做的更正

int max(int a, int b)
{
    return a > b ? a : b ;
}

int min(int a, int b)
{
    return a < b ? a : b ;
}

int main()
{
    int (*foo)(int a, int b);
    char *str;
    int a, b;
    str = (char  *)malloc(5);
    printf("Enter the what you want to calculate min or max\n");
    scanf("%s", str);
    printf("Enter the two values\n");
    scanf("%d %d", &a, &b);

    foo = str;

    printf("%d\n", (*foo)(a, b));
    return 0;

}

嘗試這樣的事情:

int max(int a, int b)
{
    return a > b ? a : b ;
}

int min(int a, int b)
{
    return a < b ? a : b ;
}

typedef struct {
    int (*fp)(int, int);
    const char *name;
} func_with_name_t;

func_with_name_t functions[] = {
    {min, "min"},
    {max, "max"},
    {NULL, NULL}    // delimiter   
};

int main()
{
    char *str;
    int a, b, i;
    str = (char  *)malloc(5);
    printf("Enter the what you want to calculate min or max\n");
    scanf("%s", str);
    printf("Enter the two values\n");
    scanf("%d %d", &a, &b);

    for (i = 0; functions[i].name != NULL; i++) {
        if (!strcmp(str, functions[i].name)) {
            printf("%d\n", functions[i].fp(a, b));
            break;
        }
    }

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM