尝试访问结构中的指针时失败

failed while trying to reach pointer in struct

我的项目是构建书籍结构 - 并用用户参数填充它。

涉及动态分配、数组和指针。

我的 book 结构如下:

struct BOOK
{
    char* author;
    char** genders;
    int totalGenders;
    char* name;
    int* chapterPages;
    int totalChapters;

}typedef book;

当我尝试访问作者姓名时,结构中的第 1 行:

struct BOOK
{
    char* author;

我没有这样做..我的主要代码:

int main()
{
    book* b;
    char authorChar[10] = { 0 };
    int authorLen;
    char* authorName;


    // get author name
    puts("please enter the name of the author");
    scanf("%s", &authorChar);
    authorLen = strlen(authorChar);
    printf("%d", authorLen);    //print to see that lentgh is correct.

    authorName = (char*)calloc(authorLen, sizeof(char));
    strcpy(authorName, authorChar);
    puts("\n");
    b->author = authorName;

    printf("%d", b->author);

当我调试时,我在这一行遇到了问题:

b->author = authorName;

有什么想法吗? :)

问题出在下面一行

  b->author = authorName;

此时,b没有分配内存,即b是一个未初始化的指针。它指向某个不是 valid 的随机内存位置。任何访问无效内存的尝试都会调用 undefined behavior.

您可以使用以下任一方法解决问题:

  • 在使用前动态分配内存给b,例如b = malloc(sizeof*b);并检查是否成功。

  • b 定义为 book 类型的变量,而不是 pointer-to-type.

也就是说,int main() 至少应该是 int main(void) 才能符合标准。

您忘记为 b 变量分配内存。

b = malloc(sizeof(book));
b->author = malloc(sizeof(100000)); // replace value for the size you want