从函数返回数组/指针 [英] Returning Arrays/Pointers from a function

查看:54
本文介绍了从函数返回数组/指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我最初尝试过:

/* 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?

谢谢.

推荐答案

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

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.

这篇关于从函数返回数组/指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆