2012-10-24 47 views
0

我有一個結構通過嵌套它作爲一個參數閱讀定義爲結構陣列閱讀()問題

struct my_struct { 
    struct hdr_str hdr; 
    char *content; 
}; 

我試圖將內容傳遞在my_struct的第一要素my_struct ()

我有什麼是

struct my_struct[5]; 

讀取被定義爲

ssize_t read(int fd, void *buf, size_t count); 

,我試圖把它作爲

read(fd, my_struct[0].content, count) 

但我收到-1作爲返回值,並將errno = EFAULT(無效地址)

任何想法如何創建讀讀入char *在結構數組中?

回答

2

您需要爲read分配內存才能將數據複製到。

如果你知道你會讀出的數據的最大大小,你可以改變my_struct到

struct my_struct { 
    struct hdr_str hdr; 
    char content[MAX_CONTENT_LENGTH]; 
}; 

其中MAX_CONTENT_LENGTH是#define'd由您將知道最大長度。

另外,按需分配my_struct.content一旦你知道如何讀取的字節數

my_struct.content = malloc(count); 
read(fd, my_struct[0].content, count); 

如果你這樣做,一定要在以後使用free上my_struct.content到內存返回到系統。