I'm trying to return an array of integers from a function, sort the numbers then pass everything back to main. I haven't allocated and freed memory in this piece of code. I was just trying to see if it would actually work. The compiler flags an error for the statement b=sort(a)
. It says that it is not assignable, which would make sense. The input integers are not pointers. Is there a way to declare an array of integers as pointers? such as :
int *a[5]={3,4}
#include <stdio.h>
#include <stdlib.h>
int *sort(int *input_array);
int *sort(int *input_array)
{
return input_array;
}
int main()
{
int a[5]={3,4};
int b[5];
b=sort(a);
return 0;
}
When you create an array, you cannot assign to the array itself (only to the elements). Besides, since when you pass an array, you're passing it by reference, sort()
would modify the array, making it unneeded to return it.
What you're looking for is either of: sorting the original array, which would be like this:
void sort (int * array);
void sort (int * array) {
// do stuff on the array
}
int main (void) {
int a[5] = {1, 46, 52, -2, 33};
sort(a); // result is still in a
return 0;
}
Or creating a copy and sorting it, which would be like this:
#include <stdlib.h>
#include <string.h>
int * sort (int * array, unsigned size);
int * sort (int * array, unsigned size) {
int * copy = malloc(sizeof(int) * size);
memcpy(copy, array, size * sizeof(int));
// sort it somehow
return copy;
}
int main (void) {
int a[5] = {1, 46, 52, -2, 33};
int * b; // pointer because I need to assign to the pointer itself
b = sort(a, (sizeof a) / (sizeof *a)); // now result is in b, a is unchanged
// do something with b
free(b); // you have to
return 0;
}
You can't assign arrays, they're not "first class citizens" but instead behave much like pointers.
You need something like:
int a[] = { 3, 4 };
int *b;
b = sort(a, sizeof a / sizeof *a);
The sizeof
expression is needed to compute the length of the array, the sort()
function can't determine that from the bare pointer it gets passed.
UPDATE: The above assumes that you won't be changing the input array, but if you do then (as pointed out in a comment, thanks) the return value is of course not needed since the caller's a
will have changed when the sort()
call returns.
If you are passing array - a pointer of int
, you don't need to return a changed array. The array that you passed will get changed.
As @unwind suggested, you should pass number of elements to the function also so that the function knows how many elements are there in the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With