0

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;
Vincenzo Cosi
  • 163
  • 1
  • 12
  • 3
    That is just perverse. – Weather Vane Jul 19 '17 at 18:29
  • 1
    If **pone* points to one and **ptwo* points to two then *memcpy(one,two,sizeof(one));* should to it. – Arif Burhan Jul 19 '17 at 18:30
  • So you copy a pointer but not what it points to. Suppose you then `free` the pointer in the first `struct`. Doomed. – Weather Vane Jul 19 '17 at 18:31
  • 1
    Not really, not automatically. The typical workaround is to extract the common fields into a parent structure which may be embedded into both structures and copied. Or you may play nasty games with half-baked introspection to register each individual member's name, offset and type. Then write a function to copy matching fields. Or use code generation to preprocess the structure definitions and generate suitable copying code offline. – doynax Jul 19 '17 at 18:31
  • free should only be used in conjunction with malloc() , these are static structures. – Arif Burhan Jul 19 '17 at 18:35
  • use memcpy https://stackoverflow.com/questions/4931123/copying-one-structure-to-another – EsmaeelE Jul 19 '17 at 21:23

3 Answers3

3

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.

dbush
  • 186,650
  • 20
  • 189
  • 240
0

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)
-2

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));
}
Jonathon S.
  • 1,641
  • 1
  • 10
  • 17