这是学习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;
};
我试图初始化数据库结构。但我越来越segfault
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的初始化值”()
可能有人建议我可能是错在这里做什么?
为什么你使用'rows'作为数组,当它只是一个'int'? – tay10r
使用调试器查看导致段错误的原因。最有可能''conn-> db'没有初始化或者什么 –
@Ajit你应该包括你如何调用'Database_create' – tay10r