使用多层间接时出现段错误
当分配并尝试访问指向指针的指针数组时:
void tester(char ***p)
{
int i;
char **pp;
pp = *p;
pp = calloc(10, sizeof(*pp));
for (i = 0; i < 10; i++)
printf("%d = %p\n", i, pp[i]);
*p = pp;
}
void tester_broken(char ***p)
{
int i;
*p = calloc(10, sizeof(**p));
for (i = 0; i < 10; i++)
printf("%d = %p\n", i, *p[i]);
}
int main(void)
{
char **a;
tester(&a);
tester_broken(&a);
return 0;
}
任何人都可以解释为什么其中一个有效而其他段错误?
When allocating and then attempting to access an array of pointers to pointers:
void tester(char ***p)
{
int i;
char **pp;
pp = *p;
pp = calloc(10, sizeof(*pp));
for (i = 0; i < 10; i++)
printf("%d = %p\n", i, pp[i]);
*p = pp;
}
void tester_broken(char ***p)
{
int i;
*p = calloc(10, sizeof(**p));
for (i = 0; i < 10; i++)
printf("%d = %p\n", i, *p[i]);
}
int main(void)
{
char **a;
tester(&a);
tester_broken(&a);
return 0;
}
Can anyone explain why one of these works and the other seg faults?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个优先级问题。尝试:
方括号运算符(数组下标)比星号运算符(取消引用)绑定更紧密。括号使您的意图明确。
It's a precedence problem. Try:
The bracket operator (array subscripting) binds tighter than the asterisk operator (dereference). The parentheses make your intent explict.