我是C语言的新手,我需要一些处理数组的方法的帮助。来自Java编程,我习惯于说int [] method()以返回数组。但是,我发现使用C时,必须在返回数组时使用数组指针。作为一个新的程序员,即使在我浏览过许多论坛的情况下,我也完全不理解这一点。

基本上,我试图编写一个返回C语言中的char数组的方法。我将为该方法(让其称为returnArray)提供一个数组。它将根据先前的数组创建一个新数组,并返回指向它的指针。我只需要一些帮助,以了解如何开始使用它以及如何将指针从数组中发送出去后如何读取它。任何帮助解释这一点表示赞赏。

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

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?
}


函数的调用者

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)
}

10-04 14:22
查看更多