Passing two different structs into same function

后端 未结 4 1017
萌比男神i
萌比男神i 2021-01-06 01:34

I have 2 different sized structs and I would like to have one function in which I can pass them into. However, I do not know how to define the parameter of the function to

4条回答
  •  独厮守ぢ
    2021-01-06 02:11

    As dasblinkenlight put it, if you wanted to be able to pass two different structs into the functions, using void * to pass a generic pointer would be the way to go, however, doing so is not type safe and could easily lead to error-prone code.

    What functionality are you trying to achieve by having two separate structs? You could consider combining the information into a single struct instead, and having a print function that prints out all non zero values?

    Forgive the perhaps non-optimal c code, I am far from an expert, this is just to illustrate the point :)

    typedef struct datastruct {
        int a;
        int b;
        float c;
    } datastruct;
    
    void printData(datastruct *d){
    
        printf("Data:\n")
        printf((d->a) ? "a=%d", a : "");
        printf((d->b) ? "b=%d", b : "");
        printf((d->c) ? "c=%.2f", c : "");
        printf("\n");
    }
    
    int main(void) {
    
        datastruct data = {0};
        /* now set values as needed */
    
        printData(&data);
    
        return 0;
    }
    

提交回复
热议问题