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

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

问题描述

我想创建一个由字符的字符串派生的新整数数组。例如:

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.

无效splitString(为const char的String [],INT结果[],INT N){
    // ....
}

这是有利的,因为无论他们想要的主叫方可以分配内存。

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

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

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