c - 使用 C 返回数组

标签 c arrays pointers char

我对 C 语言比较陌生,我需要一些有关处理数组的方法的帮助。来自 Java 编程,我习惯于使用 int [] method() 来返回一个数组。然而,我发现使用 C 语言返回数组时必须使用指针。作为一个新程序员,我真的完全不明白这一点,即使我浏览了很多论坛。

基本上,我正在尝试编写一个用 C 语言返回 char 数组的方法。我将提供带有数组的方法(我们称之为 returnArray)。它将根据前一个数组创建一个新数组并返回指向它的指针。我只需要一些帮助来了解如何开始以及如何在指针从数组中发送出去后读取指针。

数组返回函数的建议代码格式

char *returnArray(char array []){
  char returned [10];
  // Methods to pull values from the array, interpret
  // them, and then create a new array
  return &(returned[0]); // Is this correct?
}

函数的调用者

int main(){
  int i = 0;
  char array [] = {1, 0, 0, 0, 0, 1, 1};
  char arrayCount = 0;
  char* returnedArray = returnArray(&arrayCount); // Is this correct?
  for (i=0; i<10; i++)
    printf(%d, ",", returnedArray[i]); // Is this correctly formatted?
}

我还没有对此进行测试,因为我的 C 编译器目前无法工作,但我想弄清楚这一点。

最佳答案

你不能从 C 中的函数返回数组。你也不能(不应该)这样做:

char *returnArray(char array []){
 char returned [10];
 //methods to pull values from array, interpret them, and then create new array
 return &(returned[0]); //is this correct?
} 

returned 是使用自动存储持续时间创建的,一旦它离开其声明范围(即函数返回时),对其的引用将变得无效。

您需要在函数内部动态分配内存或填充调用者提供的预分配缓冲区。

选项 1:

动态分配函数内部的内存(调用者负责释放ret)

char *foo(int count) {
    char *ret = malloc(count);
    if(!ret)
        return NULL;

    for(int i = 0; i < count; ++i) 
        ret[i] = i;

    return ret;
}

这样调用它:

int main() {
    char *p = foo(10);
    if(p) {
        // do stuff with p
        free(p);
    }

    return 0;
}

选项 2:

填充调用者提供的预分配缓冲区(调用者分配buf并传递给函数)

void foo(char *buf, int count) {
    for(int i = 0; i < count; ++i)
        buf[i] = i;
}

并这样调用它:

int main() {
    char arr[10] = {0};
    foo(arr, 10);
    // No need to deallocate because we allocated 
    // arr with automatic storage duration.
    // If we had dynamically allocated it
    // (i.e. malloc or some variant) then we 
    // would need to call free(arr)
}

关于c - 使用 C 返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56689554/

相关文章:

c - 函数在 'gcc -O2' 优化为无限循环

取消引用函数结果的 PHP 语法

objective-c - C 数组与 Obj-C 数组

c - 指向无效位置的指针

c - 字符串读/写时出错

c - 读取结构矩阵会跳过每个结构的最后一个成员变量

c# - C# 中的 C 位域

java - 打印数组中设定值之间的所有数字

c++ - 在指针 vector 中搜索字符串

c++ - 如何使用方法指针作为另一个方法的参数?