Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c - Dynamic allocation of 2D array within function (using pointers to return adress of allocated object)

I'd /ike to know, how to pass pointers to dynamically allocated arrays using function arguments. This function is supposed to allocate array 10x10 (checks skipped for simplicity sake). Is this possible? What am i doing wrong? Thanks in advance.

int array_allocate2DArray ( int **array, unsigned int size_x, unsigned int size_y)
{
    array = malloc (size_x * sizeof(int *));

    for (int i = 0; i < size_x; i++)
        array[i] = malloc(size_y * sizeof(int));

    return 0;
}

int main()
{
    int **array;
    array_allocate2DArray (*&array, 10, 10);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I came across this post when I was facing a similar problem (I was looking for a way to dynamically allocate an array of strings in C). I prefer to return the array pointer from the function. The following worked for me (I adapted it for your array of integers). I arbitrarily set 99 for each value so I could see them printed out in main.

int **array_allocate2DArray(unsigned int size_x, unsigned int size_y)
{
        int i;
        int **arr;

        arr = malloc(size_x*(sizeof(int*)));

        for (i=0 ; i<size_x ; i++){
                arr[i] = malloc(size_y);
                *arr[i] = 99;
        }

        return arr;

}

int main(void)
{
        int i;
        int **arr;

        arr = array_allocate2DArray(10, 10);

        for (i=0 ; i<10 ; i++){
                printf("%d
", *arr[i]);
                free(arr[i]);
        }
        free(arr);

        return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...