2012-10-24 48 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到内存返回到系统。