C语言 从函数返回数组/指针

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5378768/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:06:47  来源:igfitidea点击:

Returning Arrays/Pointers from a function

carraysfunctionpointers

提问by Garee

I am trying to create a new integer array which is derived from a string of characters. For example :

我正在尝试创建一个从字符串派生的新整数数组。例如 :

char x[] = "12334 23845 32084";  

int y[] = { 12334, 23845, 32084 };

I am having trouble understanding how to return an array ( which I understand isn't possible ) from a function.

我无法理解如何从函数返回数组(我认为这是不可能的)。

I originally tried :

我最初尝试:

/* Convert string of integers into int array. */
int * splitString( char string[], int n )
{
    int newArray[n];

    // CODE

    return ( newArray );
}

int main( void )
{
    int x[n] = splitString( string, n );

    return ( 0 );
}

I later learned that you can not do this.

后来我才知道你不能这样做。

How do pointers work in regards to functions?

指针在函数中是如何工作的?

Thank you.

谢谢你。

回答by Puppy

Typically, you require the caller to pass in the result array.

通常,您需要调用者传入结果数组。

void splitString( const char string[], int result[], int n) {
    //....
}

This is advantageous because the caller can allocate that memory wherever they want.

这是有利的,因为调用者可以在他们想要的任何地方分配该内存。

回答by Brian Roach

The problem is you're returning a pointer to something on the stack. You need to create your array on the heap, then free it when you're done:

问题是你返回了一个指向堆栈上的东西的指针。您需要在堆上创建数组,然后在完成后释放它:

int * splitString( char string[], int n )
{
    int *newArray = malloc(sizeof(int) * n);

    // CODE

    return ( newArray );
}

int main( void )
{
    int *x = splitString( string, n );

    // use it

    free(x);

    return ( 0 );
}

回答by Prasoon Saurav

int * splitString( char string[], int n )
{
    int newArray[n];
    return ( newArray );
}

This is very bad! The array newArraylocal to the function gets destroyed when the function returns. You'd be left out with a dangling pointer and using it would invoke undefined behaviour.

这真是太糟了!newArray当函数返回时,函数的局部数组被销毁。你会被一个悬空指针排除在外,使用它会调用未定义的行为。

You can't return an array from a function. The best you can do is

您不能从函数返回数组。你能做的最好的是

int * splitString( char string[], int n )
{
    int *newArray = malloc(n*sizeof(int)); // the array gets allocated on the heap rather than on the stack(1)
    // Code 
    return ( newArray );
}

Don't forget to free the allocated memory.

不要忘记释放分配的内存。

(1) Note that the standard doesn't use/define the term stack or heap as such.

(1) 请注意,该标准并未使用/定义术语堆栈或堆。

回答by Jacob

Rather than returning an array with return (newArray), you return a pointerto the first element of newArray.

return (newArray)返回一个指向newArray 第一个元素的指针,而不是用 返回一个数组。

The problem is that you're allocating the array the wrong way. If you instantiate it with int newArray[n], memory gets allocated on the current stack frame. That memory will be freed as soon as your function returns, and whatever was in the array will be garbage. Instead, do the following:

问题是您以错误的方式分配数组。如果用 实例化它int newArray[n],内存会在当前堆栈帧上分配。一旦您的函数返回,该内存将被释放,并且数组中的任何内容都将是垃圾。相反,请执行以下操作:

int *newArray = malloc(n * sizeof(int));
// etc.
return newArray

By using malloc, you allocate memory on the heap, where it will survive past the end of the current stack frame. Just remember to free(newArray)somewhere in your program when you're done.

通过使用malloc,您可以在堆上分配内存,它将在当前堆栈帧结束后继续存在。完成后,请记住free(newArray)在程序中的某个位置。

回答by jcoder

You can wrap an array in a structure and then return an instance of the structure. I'm mentioning this for completeness, it's not really something you'd want to do as it's ugly and there are better alternatives.

您可以将数组包装在结构中,然后返回该结构的实例。我提到这一点是为了完整性,这并不是你真正想要做的事情,因为它很丑,而且有更好的选择。

#include <stdio.h>

struct retval
{
    int a[10];
};

struct retval test()
{
    struct retval v = {{1, 5, 6}};
    return v;
}

int main()
{
    struct retval data = test();
    printf("%d %d\n", data.a[1], data.a[2]);
}

回答by TanyaV

The main issue i see is trying to return memory which you allocated on the stack, which becomes invalid once the function it was allocated in reutrns (in this case your splitString). What you can do is allocate the memory in the caller, and pass a pointer to the beginning of the array into the function

我看到的主要问题是试图返回您在堆栈上分配的内存,一旦在 reutrns 中分配了它的函数(在这种情况下是您的 splitString),该内存就变得无效。您可以做的是在调用者中分配内存,并将指向数组开头的指针传递给函数

/* Convert string of integers into int array. */
void splitString(char string[], int *out_arr, int n )
{

    // code that fills each cell of out_arr

}

int main( void )
{
    int x[n];
    splitString( string,(int *)x, n );

    return ( 0 );
}

回答by Dr McKay

Of course it's possible. This is the way I prefer: int func(int** results)

当然有可能。这是我更喜欢的方式: int func(int** results)

Function returns number of elements in results. resultsis a pointer to an int array.

函数返回 中的元素数resultsresults是一个指向 int 数组的指针。