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 *'
using a for-loop my microcontroller crashes:
for (int i = 0; i < 3; i++) {
msg->data[i] = data_to_be_copied[i];
}
Same happens, when I try to use memcpy:
memcpy(msg->data, data_to_be_copied, 3);
What am I missing here?
Thanks for your help.
msg->data
is an array.
As such, it does not have an l-value, and you cannot change it.
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.
Assuming that you have data_t* msg
declared in the right place, you still need to initialize it:
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.
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
).
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 ).
You have some possibilities:
memcpy (msg->data, data_to_be_copied, 3);
or change data_to_be_copied to
data_t data_to_be_copied;
and assign the whole thing: *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.
If it crashes, then most likely msg is NULL or some uninitialised pointer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.