简体   繁体   English

将数组复制到C中的Struct成员

[英]copy Array to Member of Struct in C

I'm trying to transmit data wireless. 我正在尝试无线传输数据。 My payload-struct looks like this: 我的有效负载结构如下所示:

typedef struct
{
   uint8_t data[3];
} data_t

I also have an array in my code: 我的代码中也有一个数组:

uint8_t data_to_be_copied[3];

if I try to simply assign each other I get the following error: 如果我尝试简单地互相分配,则会出现以下错误:

msg->data = data_to_be_copied;

incompatible types when assigning to type 'uint8_t[3]' from type 'uint8_t *' 从'uint8_t *'类型分配给'uint8_t [3]'类型时不兼容的类型

using a for-loop my microcontroller crashes: 使用for循环,我的微控制器崩溃:

for (int i = 0; i < 3; i++) {
  msg->data[i] = data_to_be_copied[i];
}

Same happens, when I try to use memcpy: 当我尝试使用memcpy时,也会发生同样的情况:

memcpy(msg->data, data_to_be_copied, 3);

What am I missing here? 我在这里想念什么?

Thanks for your help. 谢谢你的帮助。

msg->data is an array. msg->data是一个数组。

As such, it does not have an l-value, and you cannot change it. 因此,它没有l值,因此无法更改。

That's why you're getting a compilation error for the first option mentioned above. 这就是为什么您遇到上述第一个选项的编译错误的原因。

For the second and third options mentioned above, you're getting a memory access violation during runtime, probably because your msg variable is not initialized to point to a valid memory address. 对于上面提到的第二个和第三个选项,在运行时会遇到内存访问冲突,这可能是因为msg变量未初始化为指向有效的内存地址。

Assuming that you have data_t* msg declared in the right place, you still need to initialize it: 假设您在正确的位置声明了data_t* msg ,您仍然需要对其进行初始化:

data_t* msg = (data_t*)malloc(sizeof(data_t));

You should also make sure that you free(msg) at a later point in the execution of your program. 您还应确保在以后执行程序时free(msg)

BTW, you have not specified the entire structure of your program, but a simple data_t msg instance might be sufficient for your needs (in which case, you don't need to use the malloc and the free ). 顺便说一句,您尚未指定程序的整个结构,但是一个简单的data_t msg实例就可以满足您的需要(在这种情况下,您无需使用mallocfree )。

And as mentioned in a comment by @Shahbaz , if you do end up using malloc and free , then you need to make sure that your platform (OS or BSP) supports dynamic memory allocation (AKA heap ). 并且在由@Shahbaz的评论中提到,如果最终使用mallocfree ,那么你需要确保你的平台(操作系统或BSP)支持动态内存分配(AKA )。

You have some possibilities: 您有一些可能:

memcpy (msg->data, data_to_be_copied, 3); memcpy(msg-> data,data_to_be_copied,3);

or change data_to_be_copied to 或将data_to_be_copied更改为

data_t data_to_be_copied;

and assign the whole thing: *msg = data_to_be_copied 并分配整个内容:* msg = data_to_be_copied

or if msg has actually more members, declare a struct that has an array of three chars as its only member. 或者,如果msg实际上有更多成员,则声明具有三个字符数组的结构作为其唯一成员。

If it crashes, then most likely msg is NULL or some uninitialised pointer. 如果崩溃,则很有可能味精为NULL或一些未初始化的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM