Create a C function that accepts parameters of different data types

前端 未结 6 1274
陌清茗
陌清茗 2021-02-09 02:07

I\'m relatively new to the C programming language, and I\'m trying to figure out how to create a function that can accept different types of data as parameters. The function is

6条回答
  •  别跟我提以往
    2021-02-09 03:08

    In either case, you will need some sort of type-inferencing system to tell the C compiler which function to call. Which means, you will need to know, before-hand the type of array you might send in as a parameter to this "super function" of yours.

    There is no "auto-type-inferencing" in C that can let you reflect upon the type of data at runtime. Better yet, you might have to write your own runtime environment for this to happen.

    A slightly trivial hackish way to do this:

    #include 
    
    size_t GetLengthOfArray(size_t sizeOfOneElementInArray, size_t sizeOfTheArrayInBytes)
    {
       return sizeOfTheArrayInBytes/sizeOfOneElementInArray; 
    }
    int main(int argc, char *argv[])
    {
       char cArr[10] = {'A','B','C','D','E','F','G','H','I','J'};
       int iArr[5] = {10,20,30,40,50};
       printf("%d is the length of cArr\n%d is the length of iArr",GetLengthOfArray(sizeof(cArr[0]),sizeof(cArr)),
                                                                   GetLengthOfArray(sizeof(iArr[0]),sizeof(iArr)));
       return 0;
    }
    

提交回复
热议问题