gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:34:01 24 4
gpt4 key购买 nike

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

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

我的 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是一个未初始化的指针。它指向某个不是有效 的随机内存位置。任何访问无效内存的尝试都会调用 undefined behavior .

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

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

  • b 定义为 book 类型的变量,而不是指向类型的指针。

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

关于c - 尝试访问结构中的指针时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34764671/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com