這是我關於學習C堅硬方式EX17,我越來越接近第三個問題,但還沒有解決它:)動態調整結構 - 學習C困難的方法
我有以下代碼:
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
,因爲我認爲這是因爲它需要一塊內存。任何人都可以幫助指出我做錯了什麼?感謝
'的malloc(10320)'** **仍然看起來可怕的錯誤。使用'sizeof'。真。用它。 – 2014-01-22 22:21:51
究竟是什麼意思* Database_create錯誤*?請用'sizeof'運算符將'malloc(10320)'替換爲適當的大小。 –
感謝您的回覆,我知道molloc(10320)不是很好的做法,我只是測試它是否有幫助。 @FilipeGonçalves在我添加malloc之前我得到了'使用8號大小的未初始化值'的錯誤。 –