Make the return type int *
.
Create a local variable int *result = malloc(sizeof(int) * 2);
and put your a
and b
or whatever you need to return in result
.
When you call the function, assign the result to an int *
.
int *res;
res = doStuff(a, b);
a = res[0];
b = res[1];
malloc
allocates space for result
on the heap. Its input is the number of bytes you need.
2 int
s, 4 bytes per int
-> 8 bytes == 2*sizeof(int)
The problem is that every time you call your function, you will keep allocating more and more space. C doesn't do garbage collection for you, so when you're done using your int *res
, you should free that space by calling free(res)
.
Further Details:
In C#, you would initialize an array like this: int[] result = new result[2];
Have you every tried printing an array like this Console.WriteLine(myarray);
. It doesn't work does it? C# I believe prints something like System.Int32[]
. If you did this in Java (System.out.println(myarray);
), it would print some weird number.
That number is actually the address of the array.
When you reference your array myarray
, you are actually referencing the address of the array. When you do something like myarray[1]
, you are getting the address of myarray
, adding to it 1*sizeof(int)
and fetching that value.
In C, you can define arrays in the typical way: int arr[2];
which allocates space for 2 ints.
Alternatively, you can do: int *arr;
which defines a pointer (or address). However, you need to tell it to allocate space for integers. As it is now, arr
doesn't really point to anything. You allocate space by calling malloc
: arr = malloc(2*sizeof(int));
which dynamically allocates space for 2 integers.
Now you can put stuff in your array. arr[0] = 1
.
The []
is effectively doing pointer arithmetic.
arr[1] is the same as *(arr + 1)
arr + 1
is getting the address of the array and adding 1 to it. C sees that you're adding to an int *
so it interprets 1 to mean 1 int (4 bytes). The *
operator dereferences the address, which means it follows the pointer and gets the value stored at that address.
If printing arr
gives you 0x1000
, arr+1
gives you 0x1004
and *
will return the int stored at 0x1004
.
On to returning arrays in functions.
In C, you can't return an array like in C# (int[] function(...)
), but you can return a pointer (int *function(...)
), which you can use like an array (see above example).
The reason you want to use malloc
is because malloc
allocates space on the heap, so you can use that array after the function returns. If you defined an array like int arr[2];
, the space would be allocated on the stack, and the array wouldn't persist after the function returns.
Perhaps you should look at a tutorial to learn more about pointers. I think my answer is too lengthy and not totally relevant to the question.