[英]C Dynamically allocated a struct in an array that is inside another struct
So to try to sum this up nicely, I have a main struct that is a catalog, it contains a counter(of the books it has), the capacity(total number of books it can support, can also grow), and an array of pointers that point to another struct that contains the book information.所以为了很好地总结一下,我有一个主要的结构,它是一个目录,它包含一个计数器(它拥有的书籍)、容量(它可以支持的书籍总数,也可以增长)和一个数组指向另一个包含书籍信息的结构的指针。
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;
The exact valgrind error is:确切的 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
I am assuming this is because I am not allocating my structs/array properly, but I haven't had to dynamically allocate an array of structs inside another struct before and I believe I am confusing myself.我假设这是因为我没有正确分配我的结构/数组,但我之前不必在另一个结构中动态分配一个结构数组,我相信我自己很困惑。
EDIT: I was allocating the memory wrong see: C printing extremely weird values with printf编辑:我分配了错误的内存,请参阅: C 用 printf 打印非常奇怪的值
EDIT: As pointed out I forgot the method that calls idComp编辑:正如所指出的,我忘记了调用 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
points at an array of Books
, so what are passed to comparision function of qsort
are pointers to Books
, not pointers to pointers to Books
. cat->b
点的数组Books
,传递给的比较函数,那么什么qsort
是指向Books
,而不是指针的指针,以Books
。
Threfore, the idComp
function should be like this:因此,
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.