c - 来自三字符指针的分段错误
问题描述
我有这段代码在打印出“最喜欢的”书籍时不断导致分段错误。
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 中第一本书的书串,但是当尝试检索任何其他书籍时,它看起来是一个空指针三重取消引用它。我不明白为什么只有第一个“收藏夹”指针能够正确地取消引用,但没有更多的。任何帮助是极大的赞赏!
解决方案
char ****favorites
应该只是char ***favorites
。char *
是一个字符串,char **
是一个字符串数组,并且char ***
是指向包含字符串数组的调用者变量的指针。
*
那么你sizeof
的malloc()
通话中有太多人了。它应该始终比*
您分配的指针中的数量小 1。另外,不要在 C 中强制转换 malloc。
*(favorites +i)
视为favorites
一个数组,它相当于favorites[i]
. 但是数组是 in *favorites
,所以你需要另一个级别的间接。用于(*favorites)[i]
此。
((&titles)+(current_fav-1))
也是错误的。*titles
是标题数组,但这被titles
视为数组。这应该是(*titles)[current_fav-1]
。
最后打印的循环根本没有索引*favorites
,它只是每次都打印第一个元素。
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 = 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)[i]);
}
}
推荐阅读
- r - 含义错误: if (m < n * p && (m == 0L || (n * p)%%m)) 中的错误 stop(sprintf(ngettext(m, :
- angular - 刷新页面 nz-checkbox 显示双复选框后我该怎么办
- java - webdriver 引用变量中的元素
- postgresql - 如何将列设置为主键并从终端在 postgres 中自动递增?
- powershell - 用于从现有计算机收集 PC 硬件详细信息的 Powershell 脚本
- python - Python 如何通过使用 oauthlib 进行帐户身份验证来获取 ID_Token 以与 Open ID Connect 一起使用
- java - 将板坐标显示为 ASCII 板
- mysql - MySQL中每个查询的报告时间
- sparql - CONSTRUCT SPARQL 查询中的字段类型映射错误
- java - 如何阻止输出 excel 文件损坏?