【发布时间】:2020-09-23 01:33:58
【问题描述】:
我有这段代码在打印出“最喜欢的”书籍时不断导致分段错误。
void get_favorites(char **titles, int num_books, char ****favorites, int *num_favorites)
int i, current_fav;
printf("Of those %d books, how many do you plan to put on your favorites list?\n", num_books);
scanf("%d", num_favorites);
*favorites = (char ***)malloc(*num_favorites * sizeof(char ***));
printf("Enter the number next to each book title you want on your favorites list:\n");
for (i=0; i < *num_favorites; i++) {
scanf("%d", ¤t_fav);
*(favorites +i)=((&titles)+(current_fav-1));
}
printf("The books on your favorites list are:\n");
for (i=0; i < *num_favorites; i++) {
printf("%d. %s\n", (i+1), ***favorites);
}
我已经尝试使用 GDB 进行调试,无论出于何种原因,它似乎可以正确检索 char **titles 中第一本书的书串,但是当尝试检索任何其他书籍时,它看起来是三重解除引用时的空指针。我不明白为什么只有第一个“收藏夹”指针能够正确地取消引用,但没有更多的。非常感谢任何帮助!
【问题讨论】:
-
sizeof的参数应始终比您分配的类型少一个*。 -
*(favorites + i)应该是(*favorites)[i]。 -
你没有在最后一个循环中使用
i作为索引。 -
如果您使用数组索引语法而不是指针算法,事情会容易得多。
-
你应该展示你如何调用'get'_favorites'函数以及你作为****favorites传递的参数类型。
标签: c pointers segmentation-fault