How to return different types from a single function

前端 未结 5 1624
[愿得一人]
[愿得一人] 2020-12-18 15:57

I have the following c code :

#include 
#include 

void *func(int a) { 
    if (a==3) {
        int a_int = 5;
        int *pt         


        
5条回答
  •  无人及你
    2020-12-18 16:41

    The problem as I see it, you're trying to return the address of a local variable from a function (scope) and trying to access the returned memory from the caller. In the caller, the memory is invalid and any usage will lead to undefined behavior.

    Solution: You need to use dynamic memory allocation for the pointer (malloc()/ calloc()) which you want to return from the function. This will overcome the issue here, as the lifetime of the dynamically allocated memory is untill free()-d manually or till program termination, whichever is earlier.

    Having said that, this approach is not a good one. If all you want to return one of multiple types, go for a struct containing members for all types and use a flag to mark the type. Fill the corresponding member variable, set the flag and return the structure variable.

    For better, you can actually use an union as a member of the structure, as you only need one type at a time. For a working code, please refer to the other answer by @pmg.

提交回复
热议问题