C语言 如何从C函数创建数组返回类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14297169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make an array return type from C function?
提问by user1530249
I have tried to return the array name as shown below. Basically I am trying to make the function test return an array that can be used in main. Could you advise me as to what I need to read into more to find out how to perform a function like this?
我试图返回数组名称,如下所示。基本上我试图让函数 test 返回一个可以在 main 中使用的数组。你能告诉我我需要阅读更多内容以了解如何执行这样的功能吗?
#include <stdio.h>
int test(int size, int x){
int factorFunction[size];
factorFunction[0] = 5 + x;
factorFunction[1] = 7 + x;
factorFunction[2] = 9 + x;
return factorFunction;
}
int main(void){
int factors[2];
factors = test(2, 3);
printf("%d", factors[1]);
return 0;
}
I receive the compiler errors:
我收到编译器错误:
smallestMultiple.c:8: warning: return makes integer from pointer without a cast
smallestMultiple.c:8: warning: function returns address of local variable
smallestMultiple.c: In function ‘main':
smallestMultiple.c:13: error: incompatible types in assignment
回答by Oliver Charlesworth
Functions can't return arrays in C.
函数不能在 C 中返回数组。
However, they can return structs. And structs can contain arrays...
但是,它们可以返回结构。结构可以包含数组...
回答by Some programmer dude
You can return an array by returning a pointer (arrays decays to pointers). However, that would be bad in your case, as then you would be returning a pointer to a local variable, and that results in undefined behaviour. This is because the memory the returned pointer points to is no longer valid after the function returns, as the stack space is now reused by other functions.
您可以通过返回一个指针来返回一个数组(数组衰减为指针)。但是,这在您的情况下会很糟糕,因为您将返回一个指向局部变量的指针,这会导致未定义的行为。这是因为函数返回后返回的指针指向的内存不再有效,因为堆栈空间现在被其他函数重用。
What you should do is to pass the array and its size both as arguments to the function.
您应该做的是将数组及其大小都作为参数传递给函数。
You also have another problem in your code, and that is you use an array of size two, but write to a thirdelement.
您的代码中还有另一个问题,那就是您使用了大小为 2 的数组,但写入了第三个元素。
回答by Inisheer
You will need to allocate memory on the heap and return a pointer. C cannot return arrays from functions.
您需要在堆上分配内存并返回一个指针。C 不能从函数返回数组。
int* test(int size, int x)
{
int* factorFunction = malloc(sizeof(int) * size);
factorFunction[0] = 5 + x;
factorFunction[1] = 7 + x;
factorFunction[2] = 9 + x;
return factorFunction;
}
回答by Michael
The first line of the error messages means exactly what it says: you've declared the function as returning an int, yet you try to return a pointer.
The bigger problem (as the second line of the error messages tells you) is that the array you're trying to return a pointer to is a local array, and will therefore go out of scope when the functions returns and no longer be valid.
What you ought to do is dynamically allocate an array (i.e. a chunk of continuous memory) using mallocor newand return a pointer to it. And of course make sure you free the memory once you're done with it.
错误消息的第一行正是它所说的意思:您已将函数声明为返回一个int,但您尝试返回一个指针。
更大的问题(如错误消息的第二行告诉您的)是您尝试返回指针的数组是本地数组,因此当函数返回时将超出范围并且不再有效。
你应该做的是使用mallocor动态分配一个数组(即一块连续内存)new并返回一个指向它的指针。当然,请确保在完成后释放内存。
回答by Dmitry
Unfortunately C does not support return of arbitrary arrays nor anonymous structs from functions, but there two workarounds.
不幸的是,C 不支持从函数返回任意数组或匿名结构,但有两种解决方法。
The first workaround is to create a struct containing the array in it. It's going to have the same size as the array, be allocated on the stack ensuring space locality.
第一个解决方法是创建一个包含数组的结构。它将与数组具有相同的大小,在堆栈上分配以确保空间局部性。
e.g.
例如
typedef struct {
int arr[5];
} my_array1;
typedef struct {
int values[3];
} factorFunctionReturnType_t;
The second workaround is to invent a static memory pool(e.g. array with custom malloc/free for this array only), and this will effectively allow you to dynamically allocate memory from this pool, again, effectively returning a pointer to contiguous stack space, which is by definition an array.
第二种解决方法是创建一个静态内存池(例如,仅针对该数组使用自定义 malloc/free 的数组),这将有效地允许您从此池中动态分配内存,再次有效地返回指向连续堆栈空间的指针,从而根据定义是一个数组。
e.g.
例如
#include <stdint.h>
static uint8_t static_pool[2048];
Then implement my_alloc, my_free that manage this specific memory pool, again ensuring that the memory created is on the stack, and the memory is already owned by your application apriori(whereas malloc might allocate memory previously not accessible by application or crash if not enough memory and didn't check for fail return).
然后实现管理这个特定内存池的 my_alloc、my_free,再次确保创建的内存在堆栈上,并且内存已经被你的应用程序先验拥有(而 malloc 可能会分配之前应用程序无法访问的内存,或者如果内存不足则崩溃并且没有检查失败返回)。
The third workaround is to have the function return a local variable to a callback function; this ensures that once the function finishes, you can use the result without corrupting the stack because the function using the memory will be sitting above the scope that contains the stack.
第三种解决方法是让函数返回一个局部变量给回调函数;这确保一旦函数完成,您可以使用结果而不会破坏堆栈,因为使用内存的函数将位于包含堆栈的作用域之上。
#include <stdint.h>
#include <stdio.h>
void returnsAnArray(void (*accept)(void *)) {
char result[] = "Hello, World!";
accept(result);
}
void on_accept(void *result) {
puts((char *)result);
}
int main(int argc, char **argv)
{
returnsAnArray(on_accept);
return 0;
}
This is more efficient than a non-stacklike memory pool which needs to make decisions to avoid fragmentation, more efficient than a stacklike memory pool which just puts the result on top of the stack because it doesn't need to copy the string, and more threadsafe because the return value of the function doesn't risk being overwritten by another thread(unless a lock is used).
这比需要做出决定以避免碎片的非堆栈式内存池更有效,比仅将结果放在堆栈顶部的堆栈式内存池更有效,因为它不需要复制字符串,等等线程安全,因为函数的返回值不会有被另一个线程覆盖的风险(除非使用了锁)。
The funny thing is that all "functional programming paradigm" programs end up emphasizing that you can write C programs without any malloc by chaining callback functions, effectively allocating on the stack.
有趣的是,所有“函数式编程范式”程序最终都强调您可以通过链接回调函数在没有任何 malloc 的情况下编写 C 程序,有效地在堆栈上分配。
This has an interesting side effect of making linked lists no longer cache hostile(since callback linked lists allocated on the stack are all going to be near each other on the stack, which lets you do things like runtime string manipulation without any mallocs, and lets you built up unknown sized user inputs without doing any mallocs.
这有一个有趣的副作用,使链表不再缓存敌对(因为分配在堆栈上的回调链表都将在堆栈上彼此靠近,这使您可以在没有任何 malloc 的情况下执行运行时字符串操作等操作,并让您在不执行任何 malloc 的情况下构建了未知大小的用户输入。
回答by Howard J
C does not advocate to return the address of a local variable to outside of the function, so you would have to define the local variable as static variable.
C 不提倡将局部变量的地址返回给函数外部,因此您必须将局部变量定义为静态变量。
#include <stdio.h>
/* function to generate and return random numbers */
int * getRandom( ) {
static int r[10];
int i;
/* set the seed */
srand( (unsigned)time( NULL ) );
for ( i = 0; i < 10; ++i) {
r[i] = rand();
printf( "r[%d] = %d\n", i, r[i]);
}
return r;
}
/* main function to call above defined function */
int main () {
/* a pointer to an int */
int *p;
int i;
p = getRandom();
for ( i = 0; i < 10; i++ ) {
printf( "*(p + %d) : %d\n", i, *(p + i));
}
return 0;
}
回答by Rajat Gupta
Two points to remember:
要记住的两点:
If you want to return a single-dimension array from a function, you would have to declare a function returning a pointer.
C does not advocate to return the address of a local variable to outside of the function, so you would have to define the local variable as static variable.
如果要从函数返回单维数组,则必须声明一个返回指针的函数。
C 不提倡将局部变量的地址返回给函数外部,因此您必须将局部变量定义为静态变量。
Refer to this link: https://www.tutorialspoint.com/cprogramming/c_return_arrays_from_function.htm
请参阅此链接:https: //www.tutorialspoint.com/cprogramming/c_return_arrays_from_function.htm
回答by anil karikatti
// example for to create a array in function and it return using pointer
//if you want use malloc use header #include <stdlib.h>
int * printsquares(int a[],int size){ //to declare aa function
int* e = malloc(sizeof(int) * size); //to create array using malloc
for(int i=0;i<size;i++){
e[i]=i*i; //assign the square root values
}
return e;
}
回答by Muntasir
Firstly, you can't return an array from a function in C directly. What you can do is that you can return the address of the array in that function. In that case, the function will look something like this:
首先,您不能直接从 C 中的函数返回数组。您可以做的是,您可以在该函数中返回数组的地址。在这种情况下,该函数将如下所示:
int* test(int size, int x){
/* function body */
return factorFunction;
}
And to receive the array, you will need a pointer - not an array.
要接收数组,您将需要一个指针 - 而不是数组。
So, instead of using int factors[2];you have to use int *factors;in your mainfunction.
因此,int factors[2];您必须int *factors;在main函数中使用,而不是使用。
Secondly, even if you return the address of the array, this code won't work; because you are trying to return the address of a local array; which won't exist after the execution of the function. One easy way to solve this issue is to declare the local array (factorFunctionin this case) static.
其次,即使你返回数组的地址,这段代码也不起作用;因为您正在尝试返回本地数组的地址;在函数执行后将不存在。解决此问题的一种简单方法是将本地数组(factorFunction在本例中)声明为静态。
Considering these two matters, the function testwill look like this:
考虑到这两点,该函数test将如下所示:
int* test(int size, int x){
static int factorFunction[size];
/* function body */
return factorFunction;
}
回答by Robert Baron
Here is another way to pass back the array:
这是传回数组的另一种方法:
int test(){
static int factorFunction[3];
factorFunction[0] = 5 + x;
factorFunction[1] = 7 + x;
factorFunction[2] = 9 + x;
return factorFunction;
}
The static indicates that the variable will be allocated in a manner that it will remain in memory. So if you have a fixed size for the value and want it to remain in memory between function calls, this is one way to do it.
静态表示变量将以保留在内存中的方式分配。因此,如果您有一个固定大小的值并希望它在函数调用之间保留在内存中,这是一种方法。

