I am new in C & I am currently working with structures. I am stuck & I would be very grateful if somebody came to my rescue. So I have a function to write input data from the main module to the sub-module. It should return 0 if it writes successfully, & 1 if it doesn't succeed. I have been reading widely but I am still unsure whether to use memcpy or not. Then, on the return value I have read that memcpy returns 0 if the operation was successful and 1 if it was not. Here is that part of my code:
typedef struct {
UINT32 carnum_n;
UINT32 carnum_k;
UINT32 results[30];
UINT32 feedback[30];
UINT32 errors[30];
} MAIN;
typedef struct {
UINT32 carnum_n;
UINT32 carnum_k;
UINT32 feedback[30];
} SETTING;
/* function to copy the data from the main to the sub-module */
UINT32 Write( MAIN *data, SETTING *info)
{
sc_memcpy ( &info->carnum_k, &data->carnum_k, sizeof (SETTING));
sc_memcpy ( &info->feedback, &data->feedback, sizeof (SETTING)); //copies the array
}
I really want to get this right. Thanks in Advance:)
Question 1, your code is not correct.
When copy carnum_k
, the sizeof(SETTING)
is wrong. sizeof (SETTING)
means the size of all data in SETTING
structure. But you just need copy carnum_k
, so you need provide the size of carnum_k
, which is sizeof (UINT32)
, UINT32
is the type of carnum_k
.
memcpy ( &info->carnum_k, &data->carnum_k, sizeof (UINT32));
You can also just write an assignment info->carnum_k = data->carnum_k
.
The copy of feedback has two problem.
sizeof (SETTING)
is wrong just like when you copy carnum_k
. You can use sizeof(UINT32 [30])
, UINT32 [30]
is the type of feedback
.info->feedback
is an array address, so no need &info->feedback
, just info->feedback
. memcpy(info->feedback, data->feedback, sizeof(UINT32 [30]));
Question 2. I think you mean you may want just copy part of feedback
.
When you copy memory you need figure out src memory address, dest memory address, and the size of memory you want to copy.
so if you want copy from feedback[2]
to feedback[10]
.
&(data->feedback[2])
&(info->feedback[2])
. 9 * sizeof(UINT32)
memcpy(&(info->feedback[2]), &(data->feedback[2]), 9*sizeof(UINT32));
Question 3.
I don't known the answer.
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.