c - 从函数返回整数数组

标签 c

我试图从一个函数返回一个整数数组,对数字进行排序,然后将所有内容传回给 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/

相关文章:

c++ - 如果参数很复杂,* 和 & 运算符的作用是什么?

c++ - Big-O 用于二维数组和链表

命令行应用程序 : How to attach a child process to xcode debugger?

C - 将字符串输入到 int 变量中?

c - 使用 strcat 时如何防止 char 数组被 for 循环覆盖

使用 Axis2/C 连接到需要用户名、密码和 .cer 文件的 Web 服务

c - 为什么使用本地指针来迭代列表?

c - 将大量逻辑打包在单个 C 语句中有何优点和缺点?

c - 使用 struct 作为 "database"的任意数量单词(按字母顺序)的排序算法

C:访问第 i 个可变参数