2017-05-09 80 views
1

我的問題很簡單......我有以下結構聲明:動態增加結構「C」數組大小

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

struct Database { 
    struct Address rows[512]; 
}; 

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

現在具有明確的,我初始化我的「數據庫」我「裏面的連接「與一些虛擬地址。後來我把這個數據庫,並將其保存到文件中與我的「連接」結構裏面:

void Database_write(struct Connection *conn){ 
    rewind(conn->file); 

    int rc = fwrite(conn->db, sizeof(struct Database), 1, conn->file); 
     if(rc != 1){ 
     die("Failed to write database.\n",conn); 
     } 

    rc = fflush(conn->file); 
     if(rc == -1){ 
     die("Cannot flush database.\n",conn); 
     } 

一切都很正常,當我在我的「數據庫」結構行的預定數量爲我的地址,即512,但,如果我想動態地創建行數呢?作爲可能作爲一個參數傳遞給一個函數?我曾嘗試使用以下...

struct Database { 
    struct Address *rows; 
}; 

並與分配空間給這個指針:

conn->db->rows = (struct Address*) malloc(sizeof(struct Address)*max_rows); 

隨着MAX_ROWS被傳遞給函數設置了一個param ......但是,現在的問題是,當我去嘗試將它保存到我的「Connection」結構中的文件中時,我只保存指針「struct Address * rows;」而不是分配有空間的數據。有關如何保存此分配空間或在結構內部具有預定義數組,然後將其動態增長的任何建議?

提前致謝!

+3

你最近更新的寫入代碼看起來像不起作用是什麼? –

+0

你*有*保存指針?你只是傾銷結構以字節文件?這是一個可怕的想法。該文件只能在一部分機器上正確讀取。您需要的是將數據的邏輯表示形式寫入文件,而不僅僅是將字節存儲在進程的內存中。 – StoryTeller

+2

您必須編寫一些解析結構的序列化例程。 – Lundin

回答

3

您在正確的軌道上malloc用於創建動態數字 地址。

conn->db->rows = (struct Address*) malloc(sizeof(struct Address)*max_rows); 

但後來你有問題寫出來的Database_write到文件。這是因爲動態分配的結構不再具有硬連線的行數。您將必須更改Database_write

  1. 傳入要寫入多少行。
  2. 調整你的fwrite行寫出所有行。

您有:

void Database_write(struct Connection *conn) 
{ 
    rewind(conn->file); 

    int rc = fwrite(conn->db, sizeof(struct Database), 1, conn->file); 
    if(rc != 1){ 
     die("Failed to write database.\n",conn); 
    } 
... 

現在需要這樣的東西:

void Database_write(struct Connection *conn, int num_rows) 
{ 
    rewind(conn->file); 

    int rc = fwrite(conn->db, sizeof(struct Database), num_rows, conn->file); 
    if(rc != num_rows) 
    { 
     die("Failed to write database.\n",conn); 
    } 

... 

你也可以行數添加到您的數據庫結構,記錄 多行應該如何在文件中:

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

In這種情況下你應該fwrite要先行的文件數,然後 寫num_rows的結構地址

您可能還想查看realloc更改 飛行的行數。提示 - 小心使用,並密切關注返回值。