【问题标题】:C Dynamically allocated a struct in an array that is inside another structC在另一个结构内的数组中动态分配一个结构
【发布时间】:2020-10-23 19:11:31
【问题描述】:

所以为了很好地总结这一点,我有一个主要结构是一个目录,它包含一个计数器(它拥有的书籍),容量(它可以支持的书籍总数,也可以增长),以及指向另一个包含书籍信息的结构的指针数组。


typedef struct BooksInStock{
    int id;
    char title[MAX_TITLE];  // 38 Characters
    char author[MAX_AUTHOR]; // 20 Characters
    double level;
    int words;
}Books;


typedef struct Stock {
    Books *b;
    int count;
    int capacity;
} Stock;

确切的 valgrind 错误是:

==23844== Invalid read of size 4
==23844==    at 0x401418: idComp (catalog.c:27)
==23844==    by 0x4E6FC62: msort_with_tmp.part.0 (in /usr/lib64/libc-2.17.so)
==23844==    by 0x4E6FBD7: msort_with_tmp.part.0 (in /usr/lib64/libc-2.17.so)
==23844==    by 0x4E6FFB6: qsort_r (in /usr/lib64/libc-2.17.so)
==23844==    by 0x401AE3: listAll (catalog.c:168)
==23844==    by 0x400C13: main (reading.c:73)
==23844==  Address 0x6e61724674666172 is not stack'd, malloc'd or (recently) free'd

我假设这是因为我没有正确分配我的结构/数组,但我之前不必在另一个结构内动态分配结构数组,我相信我自己很困惑。

编辑:我分配内存错误请参阅:C printing extremely weird values with printf

编辑: 正如所指出的,我忘记了调用 idComp 的方法

void listAll(Catalog *cat)
{ // cat is just the catalog of books that have been read in already
    qsort(cat->b, cat->count, sizeof( Books ), idComp);  // idComp is called here
    if (cat->count == 0) {
        printf("No matching books");
    } else {
        printf("%5s %38s %20s %5s %7s", "ID", "Title", "Author", "Level", "Words");
        for (int i = 0; i < cat->count; i++) {
            printf("%5d %38s %20s %5.1f %7d", cat->b[i].id, cat->b[i].title,
            cat->b[i].author, cat->b[i].level, cat->b[i].words);
        }
    }
    printf("\n");
}

【问题讨论】:

  • 您没有透露levelComp 的调用方式。请发帖Minimal, Reproducible Example
  • @MikeCAT 不幸的是,我可以实际发布的内容是有限的,这是我刚来这里的学校作业,因为我无法在 2 内得到老师的回复天。
  • 这是qsort()的比较器功能?
  • @WeatherVane 是的,或者至少应该是。

标签: arrays c struct


【解决方案1】:

cat-&gt;b 指向Books 的数组,因此传递给qsort 的比较函数的是指向Books 的指针,而不是指向Books 的指针。

因此,idComp 函数应该是这样的:

static int idComp( const void *aptr, const void *bptr )
{
  const Books *a = aptr;
  const Books *b = bptr;

  if ( a->id < b->id )
    return -1;
  if ( a->id > b->id )
    return 1;
  return 0;
}

【讨论】:

    猜你喜欢
    • 2016-02-08
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 2015-11-06
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多