我正在尝试从函数返回一个整数数组,对数字进行排序然后将所有内容传递回main.我没有在这段代码中分配和释放内存.我只是想看看它是否真的有效.编译器标记语句的错误b=sort(a).它说它不可分配,这是有道理的.输入整数不是指针.有没有办法将整数数组声明为指针?如 :
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;
}
Run Code Online (Sandbox Code Playgroud)
aaa*_*789 12
创建数组时,无法分配给数组本身(仅限于元素).此外,因为当你传递一个数组时,你通过引用传递它,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;
}
Run Code Online (Sandbox Code Playgroud)
或者创建一个副本并对其进行排序,如下所示:
#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;
}
Run Code Online (Sandbox Code Playgroud)
你不能分配数组,它们不是"一等公民",而是表现得像指针.
你需要这样的东西:
int a[] = { 3, 4 };
int *b;
b = sort(a, sizeof a / sizeof *a);
Run Code Online (Sandbox Code Playgroud)
的sizeof需要表达式,来计算所述阵列的长度,sort()功能不能确定从裸指针它被传递.
更新:上面假设您不会更改输入数组,但如果您这样做(正如评论中所指出的,谢谢),当然不需要返回值,因为调用返回a时sort()调用者将会更改.