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

标签 c struct

这是我关于《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/

相关文章:

C、如何使用这个树结构

c - 使用 C 中的结构按姓名和年级对学生列表进行排序

c# - 是否可以避免序列化/反序列化并与内存映射文件 (MMF) 共享大内存对象?

c - 如何读取文件并将内容放入结构中(使用 c)?

c - ePoll 不接受一些客户

c - 服务器/客户端程序的 Makefile : "Multiple definitions of main"

python - 在Python中将字节转换为长整型

c - 无法理解循环中的值如何工作

c++ - 从用户读取整数并写入子管道,然后从中读取父管道

c++ - 了解继承多个空类时 gcc/clang 与 msvc2015 之间的不同填充规则