初始化嵌套结构

时间:2013-07-17 16:36:37

标签: c structure

从学习C这个问题来看,这是一个问题。这是C中的数据库管理系统  我有三种结构: -

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

 struct Database {
int rows;
    struct Address *row;
 };

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

我尝试初始化数据库结构。但是我得到了一个段错误

    void Database_create(struct Connection *conn, int no_of_rows)
    {
      int i = 0;
  conn->db->row_num = no_of_rows; 

      for(i = 0; i < conn->db->row_num; i++) {

      // make a prototype to initialize it
      struct Address addr;
      addr.id = i;
      addr.set = 0;

      // then just assign it
      conn->db->rows[i] = addr;
      }
  }

我已经创建了另一个为这些结构分配内存的函数。

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

    int number = conn->db->rows;

        conn->db = malloc(sizeof(struct Database));
    if(!conn->db) die("Memory error");

        conn->db->row = malloc(sizeof(*conn->db->row) * number);
        if(!conn->db->row) die("Memory error");

        if(mode == 'c') {
        conn->file = fopen(filename, "w");
        } else {
         conn->file = fopen(filename, "r+");

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

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

      return conn;
   }

valgrind在Database_open()

中说“使用大小为4的未初始化值”

有人可以在这里暗示我可能做错了吗?

1 个答案:

答案 0 :(得分:1)

db中的{p> Connectionrow中的Database是未初始化的指针。您需要初始化它们并为它们指向的结构提供存储。

您可以通过更改Connection以使其Database成为成员而不是指针来保存一些动态分配

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

您需要为数据库行分配内存

conn->db.row = malloc(no_of_rows * sizeof(*conn->db.row));
然后

Database_create看起来像

int Database_create(struct Connection *conn, int no_of_rows)
{
    int i = 0;
    conn->db.rows = no_of_rows;
    conn->db.row = malloc(no_of_rows * sizeof(*conn->db.row));
    if (conn->db.row == NULL) {
        /* out of memory */
        return 1;  /* indicate failure to caller */
    }
    for(i = 0; i < conn->db->rows; i++) {
        conn->db.row[i].id = i;
        conn->db.row[i].set = 0;
    }
    return 0; /* indicate success to caller */
}

请注意,这假设已为Connection

分配了内存
相关问题