[英]Segmentation fault from triple char pointer
我有這段代碼在打印“最喜歡的”書籍時會不斷導致分段錯誤。
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 ***
是一個指向包含字符串數組的調用者變量的指針。
那么你在malloc()
調用中的sizeof
中有太多*
。 它應該始終比您分配的指針中*
的數量少 1。 另外, 不要在 C 中強制轉換 malloc 。
*(favorites +i)
將favorites
視為一個數組,它等價於favorites[i]
。 但是數組在*favorites
,因此您需要另一個間接級別。 為此使用(*favorites)[i]
。
((&titles)+(current_fav-1))
也是錯誤的。 *titles
是*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]);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.