简体   繁体   English

C - 双指针数组 - 没有得到正确的值

[英]C - Double pointer array - not getting correct values

Context语境

I created this simple code where I store various arrays in my_arrays() function and different functions (in my example the main() ) can get the hard-coded arrays via the function my_arrays() . I created this simple code where I store various arrays in my_arrays() function and different functions (in my example the main() ) can get the hard-coded arrays via the function my_arrays() .

See the code here:请参阅此处的代码:

#include <stdio.h>

int my_arrays(int *size, int **arrays) {
    size[0] = 3;
    int array_1[3] = {1, 2, 3};
    arrays[0] = array_1;

    size[1] = 5;
    int array_2[5] = {2, 3, -5, 7, 11};
    arrays[1] = array_2;
}


int main() {
    int num_of_arrays = 2;
    int sizes[2];
    int *arrays[2];
    my_arrays(sizes, arrays);

    for (int i=0; i < num_of_arrays; i++) {
        int *array = arrays[i]; // point to sub-array
        int size = sizes[i];

        printf("array[%d]: {", i);
        for (int x=0; x < size; x++) {
            printf(" %d", array[x]);
        }
        printf(" }\n", i);
    }
    return 0;
}

In the main() I then loop through the sub-arrays and loop through each individual number and print it out.然后在main()中循环遍历子数组并遍历每个单独的数字并将其打印出来。

What I expect the code above to print out is:我希望上面的代码打印出来的是:

array[0]: { 1 2 3 }
array[1]: { 2 3 -5 7 11 }

But when compiling and running I get this:但是在编译和运行时我得到了这个:

array[0]: { 1993067712 1617605192 -2 }
array[1]: { 3936256 8 6422188 7 6422476 }

Why?为什么?

In my_arrays , array_1 and array_2 are local arrays on the stack.my_arrays中, array_1array_2是堆栈上的本地 arrays。 They will be invalid as soon as you return from my_array .一旦您从my_array返回,它们就会失效。 Now arrays[0] and arrays[1] hold pointers to invalid or "stale" memory.现在arrays[0]arrays[1]保存指向无效或“陈旧”memory 的指针。 Accessing that is undefined behaviour.访问那是未定义的行为。

(The garbage values you see shows you that your arrays have been overwritten by other uses of the stack space, probably by calls to printf .) (您看到的垃圾值表明您的 arrays 已被堆栈空间的其他用途覆盖,可能是通过调用printf 。)

If you want to create arrays, you can allocate memory on the heap:如果要创建 arrays,可以在堆上分配 memory:

int my_arrays(int *size, int **arrays)
{
    size[0] = 3;
    arrays[0] = malloc(3 * sizeof(int));
    
    arrays[0][0] = 1;
    arrays[0][1] = 2;
    arrays[0][2] = 3;

    // ... initialize other arrays ...
    
    return 0;
}

You should explicitly free it after you're done using it:使用完后,您应该明确释放它:

// at the end of main

for (int i=0; i < num_of_arrays; i++) {
    free(arrays[i]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM