【问题标题】:Segmentation fault from triple char pointer来自三字符指针的分段错误
【发布时间】: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", &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 中第一本书的书串,但是当尝试检索任何其他书籍时,它看起来是三重解除引用时的空指针。我不明白为什么只有第一个“收藏夹”指针能够正确地取消引用,但没有更多的。非常感谢任何帮助!

【问题讨论】:

  • sizeof 的参数应始终比您分配的类型少一个 *
  • *(favorites + i) 应该是(*favorites)[i]
  • 你没有在最后一个循环中使用i作为索引。
  • 如果您使用数组索引语法而不是指针算法,事情会容易得多。
  • 你应该展示你如何调用'get'_favorites'函数以及你作为****favorites传递的参数类型。

标签: c pointers segmentation-fault


【解决方案1】:

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

那么在malloc() 调用中,您的sizeof 中有太多*。它应该始终比您分配的指针中的 * 的数量少 1。另外,don't cast malloc in C

*(favorites +i)favorites 视为一个数组,相当于favorites[i]。但是数组在*favorites,所以你需要另一个级别的间接。为此使用(*favorites)[i]

((&amp;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]);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多