gpt4 book ai didi

c - 在堆与堆栈上存储嵌套结构

转载 作者:行者123 更新时间:2023-12-04 18:12:08 25 4
gpt4 key购买 nike

我试图弄清楚堆上的结构和堆栈上的结构之间的区别。我有以下结构,用于书籍、作者和书架。 Book 有多个作者,Shelf 有多个书籍。

struct Author {
char name[NAME_LENGTH];
};

struct Book {
char title[TITLE_LENGTH];
struct Author authors[AUTHORS_PER_BOOK];
int author_count;
};

struct Shelf {
struct Book books[BOOKS_PER_SHELF];
int book_count;
};

我有一堆创建 Author 和 Book 结构的函数,具有指定的名称和标题。还有一个添加作者到书的功能。我知道 C 是严格按值传递的,所以我在 add_authors_to_book 函数中使用了指向书的指针。这些函数是在本地创建的,我假设它们在堆栈上(?)。
struct Author new_author(char name[]) {
struct Author author;
strcpy(author.name, name);

return author;
}

struct Book new_book(char title[]) {
struct Book book;
strcpy(book.title, title);

book.author_count = 0;

return book;
}

void print_book(struct Book book) {
printf("%s\nby", book.title);
int i, n;
for (i = 0, n = book.author_count; i < n; i++) {
printf(" %s,", book.authors[i].name);
}

printf("\b.\n");
}

void add_author_to_book(struct Book *book, struct Author author) {
book->authors[book->author_count] = author;
book->author_count++;
}

我希望架子在堆上。我正在为它分配内存并在下面释放它。
struct Shelf *new_shelf() {
struct Shelf *shelf = malloc(sizeof(struct Shelf));
shelf->book_count = 0;

return shelf;
}

void delete_shelf(struct Shelf *shelf) {
free(shelf);
}

void print_shelf(struct Shelf *shelf) {
printf("Shelf has the %d book(s),\n", shelf->book_count);
int i, n;
for (i = 0, n = shelf->book_count; i < n; i++) {
print_book(shelf->books[i]);
}
}

My question is regarding adding the books to the shelf. Below I am assigning the book struct to the shelf's book at it's last index. Where does this struct Book reside, on the Heap or on the Stack? Will C create clone of the entire Book structure including the authors automatically when passing it to the add_book_to_shelf? Does pass by value work with such nested structs?

Also how do you go about freeing up the memory used by books and it's authors?


void add_book_to_shelf(struct Shelf *shelf, struct Book book) {
shelf->books[shelf->book_count] = book;
shelf->book_count++;
}

这是我的测试代码,
int main(int argc, char *argv[]) {
struct Shelf *shelf = new_shelf();

struct Book book = new_book("Freakonomics");
add_author_to_book(&book, new_author("Stephen Dubner"));
add_author_to_book(&book, new_author("Steven Levitt"));

add_book_to_shelf(shelf, book);

print_shelf(shelf);
delete_shelf(shelf);
return 0;
}

最佳答案

答案是书本身就在书架上。由于您将书架结构声明为直接包含书籍,因此它包含在其中存储书籍所需的完整空间。因此,将书分配到书架实际上会将其值复制到书架中。因此,如果书架在堆栈上,则书将在堆栈上,反之亦然。

关于c - 在堆与堆栈上存储嵌套结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12399080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com