gpt4 book ai didi

C数组在被函数修改后被破坏

转载 作者:太空宇宙 更新时间:2023-11-04 01:00:30 24 4
gpt4 key购买 nike

我正在尝试编写一个 C 程序,将所有传递特定条件的结构收集到一个数组中。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Book {
char title[20];
unsigned int published;
char authors[50];
unsigned int pages;
};

unsigned int get_books_from(unsigned int year, int length, struct Book data[], struct Book results[]);

int main(int argc, char* argv[]) {
struct Book data[5];

// Init book pool inside data

struct Book books[0];
unsigned int books_count = get_books_from(1973, 5, data, books);

return 0;
}

unsigned int get_books_from(unsigned int year, int length, struct Book data[], struct Book results[]) {
results = (struct Book*) malloc(sizeof(struct Book));
unsigned int results_count = 0;

int i;
for (i = 0; i < length; i++) {
if (data[i].published == year) {
*(results + results_count) = data[i];

results = (struct Book*) realloc(results, (++results_count + 1) * sizeof(struct Book));
}
}

return results_count;
}

逻辑似乎工作正常,但是当尝试访问 get_books_from 函数之外的 books 数组内容时(它被称为 results),所有数据都已损坏。一些原始数据仍然存在,但不在正确的位置,看起来好像数据被移动了。我检查了指向 booksresults 的指针,看起来这些变量在函数完成后没有指向内存中的同一个位置。可能是什么问题?

最佳答案

您的 get_books_from 在此处更改了 results 的值:

  results = (struct Book*) realloc(results, (++results_count + 1) * sizeof(struct Book));

但是它没有为调用者提供获取results新值的方法。

更糟糕的是,您使用 data 调用 get_books_from,它是在 main 的堆栈上分配的。你不能 realloc 它。正如 realloc 的文档所说,您尝试重新分配的指针必须由之前对 malloccalloc重新分配。幸运的是,您忽略了该值。但这会导致 main 中的 struct Book data[5]; 无法理解。为什么要在栈上分配空间?

关于C数组在被函数修改后被破坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41807799/

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