如何通过引用传递一个子阵列是在动态分配的二维数组? [英] How to pass by reference a sub-array which is in a dynamically allocated 2D array?

查看:266
本文介绍了如何通过引用传递一个子阵列是在动态分配的二维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要参考子阵列,它们是动态分配的二维阵列的一部分来传递。我曾尝试以下方法,这似乎并没有工作。如果有可能的任何想法?

 无效SET1(INT *一){
    一个= malloc的(2 * sizeof的(INT));
    一个[0] = 5;
    一个[1] = 6;
}无效SET2(INT *一){
    一个= malloc的(2 * sizeof的(INT));
    一个[0] = 7;
    一个[1] = 8;
}诠释主(){
    INT ** X =的malloc(2 * sizeof的为(int *));    SET1(X [0]);
    SET2(X [1]);    返回0;
}


解决方案

您需要通过的您的子阵列的地址的,就像这个例子:

 无效集(INT **一)
{
    * A =的malloc(2 * sizeof的(INT));
    (* a)个[0] = 4;
    (* a)个[1] = 9;
}INT主要(无效)
{
    INT ** X =的malloc(2 * sizeof的为(int *));
    集(安培; X [0]);
    集(安培; X [1]);
}

只要你有需要修改的东西在调用者范围的功能,你需要去与害羞;再与害羞; FE和害羞,伦斯在函数(如我们的 *一个)而在调用者的-的地址(如&放大器; X [0] )。

(您code,相比之下,指针分配的内存分配给一个局部变量(即 myArray的),当函数返回都将丢失。而内存与它失去了一起。)

I need to pass by reference sub-arrays which are part of a dynamically allocated 2D array. I have tried the following approach, which doesn't seem to work. Any ideas if it is possible?

void set1(int *a){
    a = malloc(2*sizeof(int));
    a[0] = 5;
    a[1] = 6;
}

void set2(int *a){
    a = malloc(2*sizeof(int));
    a[0] = 7;
    a[1] = 8;
}

int main(){
    int **x = malloc(2*sizeof(int*));

    set1(x[0]);   
    set2(x[1]);

    return 0;
}

解决方案

You need to pass the address of your sub-arrays, like in this example:

void set(int ** a)
{
    *a = malloc(2 * sizeof(int));
    (*a)[0] = 4;
    (*a)[1] = 9;
}

int main(void)
{
    int ** x = malloc(2 * sizeof(int*));
    set(&x[0]);
    set(&x[1]);
}

Whenever you have a function that needs to modify something in the caller's scope, you need a de­re­fe­rence in the function (like our *a) and an address-of in the caller (like &x[0]).

(Your code, by contrast, assigns the pointer to allocated memory to a local variable (namely myArray), which is lost when the function returns. And the memory is lost along with it.)

这篇关于如何通过引用传递一个子阵列是在动态分配的二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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