创建数组时,不能分配给数组本身(仅分配给元素)。此外,由于当您传递一个数组时,您是通过引用传递它,sort()
因此会修改数组,使其不需要返回它。
您正在寻找的是:对原始数组进行排序,如下所示:
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;
}
或者创建一个副本并对其进行排序,如下所示:
#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;
}