0

Earlier I had one structure C

typedef struct c
{
    int cc;
}CS;

I used to call a library function say int GetData(CS *x) which was returning me the above structure C with data.

GetData(CS *x)

Function call used to be like:

CS CSobj;
GetData(&CSObj);

Now there are two structures say C and D

typedef struct c
{
    int cc;
}CS;
CS CSobj;

typedef struct d
{
    int dc;
    int dd;
}DS;
DS DSobj;

Function GetData() has been modified to GetData(void* x). I have to call the library function say int GetData(void* x) which will be returning me one of the above structures through that void* paramter. The return type of the function tells which structure is returned.

Problem is while calling the function GetData() how and what parameter to pass since I am unaware of which struct the function will return. Any way out of this problem?

4
  • Is it yourself that provides the implementation of GetData or is that a library of which you cannot access or change the source code? Commented May 22, 2014 at 11:52
  • Library provides me the implementation. Commented May 22, 2014 at 11:55
  • 1
    You pass a pointer to some memory which is large enough to hold the larger of the two structs. Casting and further processing is then done according to the return value of GetData(). In case the smaller struct is constructed some memory is wasted, but that's unavoidable. Commented May 22, 2014 at 11:58
  • Thanks Peter for the explanation and James for the implementation. Commented May 22, 2014 at 12:13

1 Answer 1

5

You could use a union

 // define union of two structs
    union DorC {
       DS DSobj;
       CS CSobj;
    } CorD;

 // call using union
 rc = GetData(&CorD);
 if (rc == Ctype) {
     // use CorD.CSobj;
 } else {
     // use CorD.DSobj;
 }

Warning untested un syntax checked code!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks James and Jonathan.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.