【发布时间】:2016-09-01 23:44:24
【问题描述】:
代码如下:
char* a[] = {"ls", "-l", "|", "grep", "test"};
int pipe_idx = 2;
char** ptr2 = a + (pipe_idx * sizeof(char**));
printf("%s\n", *ptr2);
基本上,这只是一个演示代码。程序获取 pipe_index(本例中为2)并跳转到正确的位置,然后打印出来。
为什么会出现分段错误?
【问题讨论】:
-
你的 ptr2 指向一个不属于你的内存。
-
怎么来的?在我看来是正确的计算
-
sizeof(char**) 是 sizeof 指针,而不是 char
-
好的,所以 sizeof(char) 成功了,但我不知道为什么。
-
因为
sizeof(char)是1,所以代码是char **ptr2 = a + pipe_idx;,是正确的。指针算术为你做乘法。
标签: c memory segmentation-fault