Double returns in C
Is it possible to return two variables in C?
I would like to return a pointer as well as a string so that I can use both outside of the function.
Is this done with an array? if so, what type of array would it be? Void?
No, you can only return one object. You can, however, return a struct type object and you can put your "multiple returns" into the struct:
typedef struct return_type
{
void* pointer_; // You should, of course, use whatever the appropriate types
char* string_; // are for the objects that you are trying to return.
};
return_type f();
You have two options:
1) Create a struct and return that
2) As parameters use pointers to what you want to change
You could do something like this,
void func(void **pVoid, char **szString)
{
pVoid = 0x1234;
szString = "Hello";
}
void* pVoid;
char* szString;
func(&pVoid, &szString);
you can return one item from the function then take a pointer as an argument that you will change. If you are given a char*
(to return a string) and you change the location it points to (don't forget to free if it's already allocated!) then the caller should see a changed value on the other end of the pointer as well. You can return a pointer as the main return value of the function.
精彩评论