首页 > 解决方案 > 来自三字符指针的分段错误

问题描述

我有这段代码在打印出“最喜欢的”书籍时不断导致分段错误。

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", &current_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 中第一本书的书串,但是当尝试检索任何其他书籍时,它看起来是一个空指针三重取消引用它。我不明白为什么只有第一个“收藏夹”指针能够正确地取消引用,但没有更多的。任何帮助是极大的赞赏!

标签: cpointerssegmentation-fault

解决方案


char ****favorites应该只是char ***favoriteschar *是一个字符串,char **是一个字符串数组,并且char ***是指向包含字符串数组的调用者变量的指针。

*那么你sizeofmalloc()通话中有太多人了。它应该始终比*您分配的指针中的数量小 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", &current_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]);
    }
}

推荐阅读