c - 初始化嵌套结构

标签 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 的未初始化值”

有人可以建议我在这里可能做错了什么吗?

最佳答案

Connection 中的

dbDatabase 中的 row 是未初始化的指针。您需要初始化它们并为它们指向的结构提供存储。

您可以通过更改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 */
}

请注意,这假设内存已分配给连接

关于c - 初始化嵌套结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17705458/

相关文章:

c - 是否有实用程序可以打印 C 程序的函数调用序列?

java - 计算这些算法的 Big O 复杂度?

c - C中struct的动态内存分配

c++ - 结构对齐/字节顺序检查

c - 如何在共享内存中的矩阵上写入?

c - 不同返回类型的 gcc 警告

c++ - 理解 char * 到 int * 的转换及其含义

c++ - 为 Arduino 编写库

jquery - 在 jQuery 中使用 OO 概念,使用 function() 并创建结构数组

java - log4j 记录器不可见