【问题标题】:failed while trying to reach pointer in struct尝试访问结构中的指针时失败
【发布时间】:2016-04-18 07:23:50
【问题描述】:

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

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

我的book 结构如下:

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

}typedef book;

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

struct BOOK
{
    char* author;

我没有这样做..我在 main 中的代码:

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;

有什么想法吗? :)

【问题讨论】:

标签: c pointers struct dynamic-memory-allocation


【解决方案1】:

问题出在下面一行

  b->author = authorName;

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

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

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

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

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

【讨论】:

  • 感谢您的回答! ,当我将b 定义为指向类型的指针时,我的错误才真正开始,而没有对其进行初始化。 (我这样做是因为在更远的将来,书本结构将只是书本数组中的一个......)。
【解决方案2】:

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

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

【讨论】:

  • ^^ 请看问题下的评论为什么不在C中转换malloc()和family的返回值。
  • 谢谢。有很长一段时间我没有用 C 编写代码。超过 4 年。
猜你喜欢
  • 2015-05-14
  • 2019-07-18
  • 2016-05-05
  • 1970-01-01
  • 2012-05-05
  • 2020-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多