简体   繁体   English

如何在C中释放指向结构的指针数组?

[英]How to deallocate array of pointers to structures in C?

I need to dynamically allocate array of structs and perform some operations on it, then deallocate the memory.我需要动态分配结构数组并对其执行一些操作,然后释放内存。 When I try to deallocate memory like that当我尝试像那样释放内存时

for (int i = 0; i < booksAmount; i++) {
    free(myArray[i])
}

Here is the link to code这是代码的链接

https://repl.it/@Xyrolle/Structures https://repl.it/@Xyrolle/Structures

I need to make so printList function will not print books array after deallocation.我需要使 printList 函数在释放后不会打印书籍数组。

Also, do you have any suggestions on how to manage memory more efficiently?另外,您对如何更有效地管理内存有什么建议吗?

Thank you.谢谢你。

The code would look like this:代码如下所示:

struct Book *booksList = NULL;
allocList(&booksList, booksAmount);

void allocList(struct Book **myArray, int booksAmount) {
    *myArray = malloc(sizeof(struct Book) * booksAmount);
    printf("memory for %d books was allocated \n", booksAmount);
}

Now to free the allocated memory.现在释放分配的内存。 You allocated memory once for the array of books, thus you'll need exactly one free :您为书籍数组分配了一次内存,因此您只需要一个free

free(booksList);

Also, note that I removed the cast from malloc .另外,请注意我从malloc删除了演员表。 This post has very good points on why you should not cast it. This post有很好的观点,说明为什么不应该投射它。

Your approach to allocate memory is not correct.您分配内存的方法不正确。 As you are using structure for each book.当您为每本书使用结构时。 You should allocate memory separately for each record.您应该为每条记录单独分配内存。 Because you may not store all book record at once.因为您可能无法一次存储所有书籍记录。 For Example: You have maximum no.例如:您有最大数量。 of books as 100, but now you have information of 10 books.书籍数量为 100,但现在您有 10 本书的信息。 With your approach memory for 90 books will be wasted.随着你的接近,90本书的记忆将被浪费。

void allocList(struct Book **myArray, int booksAmount) {
        int i;
        for(i = 0;i < booksAmount; i ++) {
            *myArray = (struct Book*) malloc(sizeof(struct Book));
        }
}

Dellaocate memory:戴尔内存:

for (i = 0; i < booksAmount; i ++) { 
    free(myArray[i]); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM