簡體   English   中英

C在另一個結構內的數組中動態分配一個結構

[英]C Dynamically allocated a struct in an array that is inside another struct

所以為了很好地總結一下,我有一個主要的結構,它是一個目錄,它包含一個計數器(它擁有的書籍)、容量(它可以支持的書籍總數,也可以增長)和一個數組指向另一個包含書籍信息的結構的指針。


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 用 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");
}

cat->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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM