我试图从一个函数返回一个整数数组,对数字进行排序,然后将所有内容传回给 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;
}
最佳答案
当你创建一个数组时,你不能分配给数组本身(只能分配给元素)。此外,由于当您传递一个数组时,您是通过引用传递它,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;
}
关于c - 从函数返回整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16604631/