Can we transfer a dynamically generated two-dimensional array from C to the return value of the function?

Asked 2 years ago, Updated 2 years ago, 31 views

#include <stdio.h>

int* array(){
    int a[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}};
    return (int*) a;
}
int main() {
    int (*a)[3] = (void*)array();
    printf("%d ", a[0][0]);
    printf("%d ", a[2][2]);
}

In fact, it's a little bit more complicated, because the size of the array is the value that we've received as a function factor, and we're going to assign elements of the array one by one, but I'm going to ask you with a simpler code that causes the same problem.

In this case, the output results in a garbage value while the first value is normal despite the output of the same index. No matter what index value you output, if you output it after the second time, the garbage value is output.

I don't have that problem when I run it with the code executor of the hash code, but instead, if I output a[2][2] after the second time, I get 0 instead of 9.

This problem does not occur when the function itself outputs before returning or writes it in the main function without defining it separately.

I checked that there is no error if you put static before int when declaring an array in the array function, but I am worried because the actual code cannot write static (because it dynamically generates an array according to the value transmitted by the factor).

I think it's a problem that I can't solve because I lack a lot of understanding of C.

How can we solve this problem?

c

2022-09-22 18:52

1 Answers

A[3][3] declared within the array function is captured in the stack area as a local variable. When you exit a function, the region is then re-used for other purposes by subsequent function calls or by local variable assignments.

Returning a pointer to a local variable is like giving a key that you used to leave a room.

Allocating memory creates a heap, so it is right to return the allocated pointer. However, if the person who receives the key uses up the key, he or she will have to get rid of the room as well.


2022-09-22 18:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.