Copy struct to struct in C

前端 未结 7 1724
北荒
北荒 2020-11-27 14:06

I want to copy an identical struct into another and later on use it as a comparance to the first one. The thing is that my compiler gives me a warning when Im doing like thi

相关标签:
7条回答
  • 2020-11-27 14:35

    For simple structures you can either use memcpy like you do, or just assign from one to the other:

    RTCclk = RTCclkBuffert;
    

    The compiler will create code to copy the structure for you.


    An important note about the copying: It's a shallow copy, just like with memcpy. That means if you have e.g. a structure containing pointers, it's only the actual pointers that will be copied and not what they point to, so after the copy you will have two pointers pointing to the same memory.

    0 讨论(0)
  • 2020-11-27 14:35

    Your memcpy code is correct.

    My guess is you are lacking an include of string.h. So the compiler assumes a wrong prototype of memcpy and thus the warning.

    Anyway, you should just assign the structs for the sake of simplicity (as Joachim Pileborg pointed out).

    0 讨论(0)
  • 2020-11-27 14:35

    memcpy expects the first two arguments to be void*.

    Try: memcpy( (void*)&RTCclk, (void*)&RTCclkBuffert, sizeof(RTCclk) );

    P.S. although not necessary, convention dictates the brackets for the sizeof operator. You can get away with a lot in C that leaves code impossible to maintain, so following convention is the mark of a good (employable) C programmer.

    0 讨论(0)
  • 2020-11-27 14:45

    Your code is correct. You can also assign one directly to the other (see Joachim Pileborg's answer).

    When you later come to compare the two structs, you need to be careful to compare the structs the long way, one member at a time, instead of using memcmp; see How do you compare structs for equality in C?

    0 讨论(0)
  • 2020-11-27 14:51

    copy structure in c you just need to assign the values as follow:

    struct RTCclk RTCclk1;
    struct RTCclk RTCclkBuffert;
    
    RTCclk1.second=3;
    RTCclk1.minute=4;
    RTCclk1.hour=5;
    
    RTCclkBuffert=RTCclk1;
    

    now RTCclkBuffert.hour will have value 5,

    RTCclkBuffert.minute will have value 4

    RTCclkBuffert.second will have value 3

    0 讨论(0)
  • 2020-11-27 14:51

    I think you should cast the pointers to (void *) to get rid of the warnings.

    memcpy((void *)&RTCclk, (void *)&RTCclkBuffert, sizeof RTCclk);
    

    Also you have use sizeof without brackets, you can use this with variables but if RTCclk was defined as an array, sizeof of will return full size of the array. If you use use sizeof with type you should use with brackets.

    sizeof(struct RTCclk)
    
    0 讨论(0)
提交回复
热议问题