2014-01-22 34 views
0

這是我關於學習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,因爲我認爲這是因爲它需要一塊內存。任何人都可以幫助指出我做錯了什麼?感謝

+3

'的malloc(10320)'** **仍然看起來可怕的錯誤。使用'sizeof'。真。用它。 – 2014-01-22 22:21:51

+0

究竟是什麼意思* Database_create錯誤*?請用'sizeof'運算符將'malloc(10320)'替換爲適當的大小。 –

+0

感謝您的回覆,我知道molloc(10320)不是很好的做法,我只是測試它是否有幫助。 @FilipeGonçalves在我添加malloc之前我得到了'使用8號大小的未初始化值'的錯誤。 –

回答

1

1) malloc的行是的sizeof(結構地址)* MAX_ROWS

conn-> DB->行= malloc的(的sizeof(結構地址)* 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; 
+0

謝謝。最後設法通過改變我的結構並採取1)和2)的建議來解決這個問題。概述我的解決方案在這裏:http://stackoverflow.com/a/21501079/847857 –

相關問題