在C中返回2D char数组 [英] Returning a 2D char array in C

查看:60
本文介绍了在C中返回2D char数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此一无所知,但我真的不明白.

I messed around with this enough but I really don't get it.

这是我想要做的:将2D字符数组作为函数的输入,更改其中的值,然后返回另一个2D字符数组.

Here is what I want to do: Take a 2D char array as an input in a function, change the values in it and then return another 2D char array.

就是这样.很简单的想法,但是想法在C语言中不容易实现.

That's it. Quite simple idea, but ideas do not get to work easily in C.

任何让我以最简单形式开始的想法都值得赞赏.谢谢.

Any idea to get me started in its simplest form is appreciated. Thanks.

推荐答案

C不会从函数返回数组.

C will not return an array from a function.

您可以做一些可能很接近的事情:

You can do several things that might be close enough:

  • 您可以将数组打包在structreturn中. C 从函数中返回struct就好了.缺点是,来回复制可能会占用大量内存:

  • You can package your array in struct and return that. C will return structs from functions just fine. The downside is this can be a lot of memory copying back and forth:

struct arr {
    int arr[50][50];
}

struct arr function(struct arr a) {
    struct arr result;
    /* operate on a.arr[i][j]
       storing into result.arr[i][j] */
    return result;
}

  • 您可以将 pointer 返回到数组.该指针必须指向您使用malloc(3)为数组分配的内存. (或者另一个不从堆栈分配内存的内存分配原语.)

  • You can return a pointer to your array. This pointer must point to memory you allocate with malloc(3) for the array. (Or another memory allocation primitive that doesn't allocate memory from the stack.)

    int **function(int param[][50]) {
        int arr[][50] = malloc(50 * 50 * sizeof int);
        /* store into arr[i][j] */
        return arr;
    }
    

  • 您可以对传递到函数中的数组指针进行操作,并在适当的位置修改.

    void function(int param[][50]) {
        /* operate on param[i][j] directly -- destroys input */
    }
    

  • 您可以将参数用作输出变量",并使用该参数返回"新数组.如果希望调用方分配内存,或者要指示成功或失败,则最好:

  • You can use a parameter as an "output variable" and use that to "return" the new array. This is best if you want the caller to allocate memory or if you want to indicate success or failure:

    int output[][50];
    
    int function(int param[][50], int &output[][50]) {
        output = malloc(50 * 50 * sizeof int);
        /* write into output[i][j] */
        return success_or_failure;
    }
    

    或者,供呼叫者分配:

    int output[50][50];
    
    void function(int param[][50], int output[][50]) {
        /* write into output[i][j] */
    }
    

  • 这篇关于在C中返回2D char数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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