如何解决来自三元字符指针的分段错误
在打印“喜欢的”书时,我的代码会不断出现分段错误。
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开头的第一本书的书串,但是,当尝试检索任何其他书籍时,它似乎是三重解引用时返回null指针。我无法弄清楚为什么只有第一个“收藏夹”指针能够正确地取消引用,而没有其他原因。任何帮助将不胜感激!
解决方法
char ****favorites
应该只是char ***favorites
。 char *
是一个字符串,char **
是一个字符串数组,而char ***
是一个指向包含字符串数组的调用方变量的指针。
然后,在*
通话中,sizeof
中的malloc()
过多。它应始终比要分配的指针中的*
的数量少1。另外,don't cast malloc in C。
*(favorites +i)
将favorites
视为一个数组,它等效于favorites[i]
。但是该数组位于*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]);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。