gpt4 book ai didi

c - 动态调整大小的结构体 - 艰难地学习 C

转载 作者:行者123 更新时间:2023-11-30 15:39:47 25 4
gpt4 key购买 nike

这是我关于《Learn C the Hard Way ex17》的第三个问题,我已经很接近了,但仍然没有解决它:)

我有以下代码:

struct Address {
int id;
int set;
char* name;
char* email;
};

struct Database {
unsigned int MAX_DATA;
unsigned int MAX_ROWS;
struct Address* rows;
};

struct Connection {
FILE *file;
struct Database *db;
};

struct Connection *Database_open(const char *filename, char mode)
{
// struct containing DB struct and DB file
struct Connection *conn = malloc(sizeof(struct Connection));
if(!conn) die("Memory error", conn);

conn->db = malloc(10320);
if(!conn->db) die("Memory error", conn);

if(mode == 'c') {
// truncate file to 0 length and create file for writing
conn->file = fopen(filename, "w");
} else {
// open for reading and writing
conn->file = fopen(filename, "r+");

if(conn->file) {
Database_load(conn);
}
}

if(!conn->file) die("Failed to open file", conn);

return conn;
}

void Database_write(struct Connection *conn)
{
// Sets the file position to the beginning of the file?
rewind(conn->file);

// writes data to stream
// fwrite(DB to be written, size of DB row, number of rows, output stream
int rc = fwrite(conn->db, 10320, 1, conn->file);
if(rc != 1) die("Failed to write database.", conn);

// flushed the output buffer. what does this do??
rc = fflush(conn->file);
if(rc == -1) die("Cannot flush database.", conn);
}

void Database_create(struct Connection *conn)
{
int i = 0;

conn->db->rows = malloc(10320);
// loop through number of rows and create 'blank rows'
for(i = 0; i < conn->db->MAX_ROWS; i++) {
// make a prototype to initialize it
struct Address addr = {.id = i, .set = 0};
// then just assign it
conn->db->rows[i] = addr;
}
}

我已经硬编码了一些值来尝试让它工作,但是 Database_create 似乎没有正确创建 conn->db 结构,就像它对原始代码所做的那样(在这里找到:http://c.learncodethehardway.org/book/ex17.html )

最初 Database_create 出错,所以我添加了 malloc,因为我认为这是因为它需要一 block 内存。谁能帮助指出我做错了什么?谢谢

最佳答案

1) malloc 行的大小为(结构地址)* MAX_ROWS

conn->db->rows = malloc(sizeof(结构地址) * MAX_ROWS);

2)您正在堆栈上创建 addr,当需要分配或复制但未分配时。

..
struct Address addr = {.id = i, .set = 0};
// then just assign it
conn->db->rows[i] = addr;
..

因此,当您离开Database_create时,addr的地址无效。

使用

memcpy(conn->db->rows +i, addr, sizeof( struct addr) );

代替

 conn->db->rows[i] = addr;

关于c - 动态调整大小的结构体 - 艰难地学习 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21295220/

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