Home>

How can I copy structure data to another structure in C language?

The copy destination structure is the copy source structure with variables added.

typedef struct {
    char sStr0 [4];/​​* It was a mistake for Str0 [4] instead of sStr0 [9] * /
    char sStr1 [4];
    char sStr2 [4];
} stTest1;
typedef struct {
    char sStr0 [4];
    char sStr1 [4];
    char sStr2 [4];
    int iVal1;
    int iVal2;
} stTest2;
// Dummy data
void main () {
    stTest1 kFrom [3] = {
        {"001", "AAA", "111"},
        {"002", "BBB", "222"},
        {"003", "CCC", "333"}
    };
    stTest2 kCopy [3];
    for (iLp = 0;iLp<3;iLp ++) {
        / * sStr0, sStr1, sStr2 want to copy kFrom data as it is * /
        kCopy [iLp] .iVal1 = iLp + 1;
        kCopy [iLp] .iVal2 = iLp + 2;
    }
    return;
}


As a result, to kCopy

{"001", "AAA", "111", 0, 1}
        {"002", "BBB", "222", 1, 2}
        {"003", "CCC", "333", 2, 3}


I want to.
Please let me know if there is a way to copy sStr0, sStr1, and sStr2 for each structure other than one item at a time.

c
  • Answer # 1

    typedef struct {
        char sStr0 [9];
        char sStr1 [4];
        char sStr2 [4];
    } stTest1;
    typedef struct {
        char sStr0 [4];
        char sStr1 [4];
        char sStr2 [4];
        int iVal1;
        int iVal2;
    } stTest2;


    typedef struct {
        char sStr0 [9];
        char sStr1 [4];
        char sStr2 [4];
    } stTest1;
    typedef struct {
        stTest1 sTest1;
        int iVal1;
        int iVal2;
    } stTest2;


    Is it common to define

    StrTest2's references to sStr0, sStr1, and sStr2 have one nest.

    The whole assignment can be done in one shot.

  • Answer # 2

    If the original structure is the previous structure, you can use the pointer to memcpy (if the original is smaller than the previous one) I can do it ...
    Looking at the code written, the member sStr0 is different in the form char [9] and char [4].

    Since this can't be done with memory copy, there is no choice but to copy one item at a time.

  • Answer # 3

      

    Please tell me if there is a way to copy the entire structure other than sStr0, sStr1, and sStr2 items one by one.

    Nomethod is guaranteed to work correctly. In the first place,stTest1andstTest2have different lengths of the leadingsStr0, so they have different memory structures.

  • Answer # 4

    How about changing the structure as follows?

    typedef struct {
        char sStr0 [4];
        char sStr1 [4];
        char sStr2 [4];
    } stTest1;
    typedef struct {
        stTest1 st;
        int iVal1;
        int iVal2;
    } stTest2;

    To access, use a hierarchical structure such asstTest2.st.sStr0.
    It can be realized with memcpy.

  • Answer # 5

    There is no universal way other than putting them one by one. Depending on the compiler, the order of elements changes and padding is automatically entered.