我有一个结构定义为
struct my_struct {
struct hdr_str hdr;
char *content;
};
我试图通过将 my_struct 中第一个元素的内容全部嵌套为 read() 的参数来传递 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(错误地址)
知道如何将 read 读入结构数组中的 char * 吗?
最佳答案
您需要为读取
分配内存以将数据复制到其中。
如果您知道要读取的数据的最大大小,则可以将 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);
如果您这样做,请确保稍后在 my_struct.content 上使用 free
将其内存返回给系统。
关于c - 结构数组作为参数传递给 read() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13056541/