使用 C 将其他结构中的值存储在结构内时出现分段错误
我有两个结构
typedef struct profile_datagram_t
{
unsigned char *src;
unsigned char *dst;
unsigned char ver;
unsigned char n;
struct profile_t profiles[MAXPROFILES];
} header;
header outObj;
struct pearson_record
{
unsigned char *src;
};
现在我想将 outObj.src 中的值 memcpy 到 struct pearson_record 的 unsigned char *src 中。
如何做到这一点?任何类型的例子或任何帮助都会有很大的帮助。提前致谢。
I have two structures
typedef struct profile_datagram_t
{
unsigned char *src;
unsigned char *dst;
unsigned char ver;
unsigned char n;
struct profile_t profiles[MAXPROFILES];
} header;
header outObj;
struct pearson_record
{
unsigned char *src;
};
Now i want to memcpy the value inside outObj.src into unsigned char *src of struct pearson_record.
How to do this?? Any kind of example or any help would be of great help. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设
outObj.src
指向包含空终止字符串的有效内存:Assuming that
outObj.src
points to valid memory which contains a null-terminated string:需要意识到的重要一点是,结构体包含指向字符串的指针;它们不包含任何字符串本身的空间。您不能使用
memcpy()
因为没有任何目标内存可供复制。一种方法是使用 strdup():The important thing to realize is that the
struct
s contain pointers to character strings; they don't contain any space for the character strings themselves. You can't usememcpy()
because there isn't any destination memory to copy into. One way to do this would be to usestrdup()
:当您创建
outObj
或pearson_record
实例时,您拥有的指针不指向任何内容。在使用它们之前,您必须使它们指向内存中的某个缓冲区。其中
length
是数据的长度。When you created
outObj
or an instance ofpearson_record
, you have pointers that don't point to anything. You have to make them point to some buffer in memory before using them.where
length
is the length of the data.