动态大小的结构 - 学习C艰难的方式

时间:2014-01-22 22:19:09

标签: 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)< / p>

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

1 个答案:

答案 0 :(得分:1)

1)    malloc行是sizeof(struct address)* MAX_ROWS

conn-&gt; db-&gt; rows = malloc(sizeof(struct address)* 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;