简体   繁体   中英

How to copy the content of a structure​ in another structure in C

I have a C program where I have two structures

struct one{
  int a;
  int b;
  char *s;
  int c;
};

struct two{
  int a;
  int e;
  char *s;
  int d;
};

Is possible to write a function that copies the values of the variables with the same type and name from struct one to struct two ? For example, in this case the function should do this

two.a = one.a;
two.s = one.s;

There's no way to automatically grab fields of a given name from a struct. While you could do something like this in Java with reflection, it can't be done in C. You just need to manually copy the relevant members.

You may write function macro like this:

#define CAT(A, B) A ## B
#define ARGS_ASSIGN(N, L, R, ...) CAT(_ARGS_ASSIGN, N) (L, R, __VA_ARGS__)
#define _ARGS_ASSIGN1(L, R, M0) L.M0 = R.M0;
#define _ARGS_ASSIGN2(L, R, M0, M1) L.M0 = R.M0; L.M1 = R.M1;
/* ... define sufficiently more */

and use in such way:

ARGS_ASSIGN(2, two, one, a, s)

In theory you could do this with a simple block copy function for your example above using the code below if you are certain that your compiler sequences the structure as sequenced in its type definition. However, I don't think it's a great idea. Block copy would be safer with two data structures of the same type as defined in one of the answers proposed above.

Example using block copy function:

void main(void)
{

    struct one{
        int a;
        int b;
        char *s;
        int c;
    };

    struct two{
        int a;
        int e;
        char *s;
        int d;
    };

    // Place code that assigns variable one here

    memcpy(&two, &one, sizeof(one));
}

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.

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