简体   繁体   English

C-通过函数调用丢失双指针

[英]C - Double Pointer getting lost through function call

Quick C question here. 快速C问题在这里。 We've been playing with double, triple, even quadruple pointers recently. 最近我们一直在使用双,三,甚至四重指针。 We though we had a grasp on things until we ran into this problem... 尽管我们对事物有所了解,直到遇到这个问题为止。

char ***data;
data_generator(&data);
char **temp = data[0];          
printf("printing temp[%d]: %s\n",0, temp[0]);
printf("printing temp[%d]: %s\n",1, temp[1]);
dosomething(temp);

int dosomething(char **array) { 

    printf("printing array[%d]: %s\n",0, array[0]);
    printf("printing array[%d]: %s\n",1, array[1]);
    ......
}

int data_generator(char ****char_data) {
    char *command1[2];
    char *command2[2];

    command1[0] = "right";
    command1[1] = "left";

    command2[0] = "up";
    command2[1] = "down";

    char **commandArray[2];

    commandArray[0] = command1;
    commandArray[1] = command2;

    number_of_commands = 2;

    if(number_of_commands > 1){
    *char_data = commandArray;
    }

    return number_of_commands - 1;
}

And this prints out... 这打印出来...

printing temp[0]: right
printing temp[1]: left
Segmentation fault

Looks like I have some misconceptions about what happens to a pointer while passed through a function. 看起来我对通过函数传递指针时会发生什么有一些误解。 Any thoughts? 有什么想法吗?

*char_data = commandArray;

You are putting the address of a stack (automatic) array in an outside memory location. 您正在将堆栈(自动)阵列的地址放在外部存储器位置。 This is a recipe for disaster (undefined behavior), since commandArray 's lifetime ends as soon as data_generator returns. 这是灾难(未定义行为)的秘诀,因为一旦data_generator返回, commandArray的生命周期就会结束。 The same is true for the elements of commandArray , which are themselves pointers to stack array elements. 对于commandArray的元素也是如此,它们本身就是指向堆栈数组元素的指针。

Change: 更改:

char *command1[2];
char *command2[2];

to: 至:

static char *command1[2];
static char *command2[2];

That will keep command1[] and command2[] in retained memory. 这样会将command1 []和command2 []保留在保留的内存中。

That, or malloc() them, as the other poster recommends, though proper use of malloc'c memory requires more considerations than I will discuss here. 就像其他发布者所建议的那样,即使用malloc()它们,尽管正确使用malloc的内存需要比我在这里讨论的更多的注意事项。

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

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