How to pass by reference a sub-array which is in a dynamically allocated 2D array?

删除回忆录丶 提交于 2019-12-14 00:15:33

问题


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;
}

回答1:


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.)




回答2:


#include <stdlib.h>
#include <stdio.h>

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

void testFunc2(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]);

    printf("value:%d\n", x[0][0]);
    printf("value:%d\n", x[0][1]);
    printf("value:%d\n", x[1][0]);
    printf("value:%d\n", x[1][1]);
    return 0;
}

Output:

value:5
value:6
value:7
value:8

Visualize the workings:

x   -->       x[0]   |   x[1]
              |            |
              \/           \/
               ?            ?

You want to change the adress where x[0] (x[1]) is pointing to. For the function being able to change that for real, you have to pass x[0] (x[1]) as a reference. Since x[0] (...) is a pointer to int ( i.e. int* ), the argument of the function should be a pointer to a pointer to int ( i.e. of type int** ) to accomplish this ( in C ). Accordingly we call set1 with the address of x[0]. In set1 we want to store the address returned by malloc at the address we get as an argument. So we dereference it and do exactly that.



来源:https://stackoverflow.com/questions/11926425/how-to-pass-by-reference-a-sub-array-which-is-in-a-dynamically-allocated-2d-arra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!