【问题标题】:How can I determine a variable type in C?如何确定 C 中的变量类型?
【发布时间】:2021-03-04 19:43:49
【问题描述】:

例如。我有这个函数-> Sort(void * param) ,其中有一个通用参数。我需要了解传递的参数的类型是什么,因为 Int 的排序与 char 不同。所以我需要类似的情况:

Sort(void *param){
     if(param is int)
        //some code
     else if(param is char)
        //some code
     else if //ecc
}

我不知道如何在 if 语句中编写代码。

【问题讨论】:

  • 我建议你看看库函数qsort()是如何在不知道类型的情况下进行管理的。除了给定元素大小,它还需要一个用例compare() 函数(也使用void*)。
  • 这个链接可能对你有帮助 -> stackoverflow.com/questions/6280055/…

标签: c function pointers variables generics


【解决方案1】:

param 的类型是 void*。地址在函数调用期间被强制转换为它,您不能只是将其“恢复”回原始类型。相反,您可以将其他信息传递给函数,例如:

void Sort(void* param, char type)
{
    if (type == 'i') {
        // some code for `int`
    } else if (type == 'c') {
        // some code for `char`
    } else if (type == 'f') {
        // some code for `float`
    } else {
        // some code ...
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多