How do I return multiple values from a function in C?

前端 未结 8 1013
深忆病人
深忆病人 2020-11-22 15:14

If I have a function that produces a result int and a result string, how do I return them both from a function?

As far as I can tell I can

8条回答
  •  心在旅途
    2020-11-22 15:41

    Since one of your result types is a string (and you're using C, not C++), I recommend passing pointers as output parameters. Use:

    void foo(int *a, char *s, int size);
    

    and call it like this:

    int a;
    char *s = (char *)malloc(100); /* I never know how much to allocate :) */
    foo(&a, s, 100);
    

    In general, prefer to do the allocation in the calling function, not inside the function itself, so that you can be as open as possible for different allocation strategies.

提交回复
热议问题