gpt4 book ai didi

c - 使用C返回数组

转载 作者:行者123 更新时间:2023-12-02 10:56:26 25 4
gpt4 key购买 nike

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com