C: copying struct/array elements

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error C: copying struct/array elements on this date .

I have a file in a known format and I want to convert it to a new format, eg.:

struct foo {
    char            bar[256];
};

struct old_format {
    char            name[128];
    struct foo      data[16];
};

struct new_format {
    int             nr;
    char            name[128];
    struct foo      data[16];
};

static struct old_format old[10];
static struct new_format new[10];

Problem: after filling ‘old’ with the data I don’t know how to copy its content to ‘new’. If I do

new[0].name = old[0].name;
new[0].data = old[0].data;

I get a compile error about assigning char * to char[128] (struct foo * to struct foo[16], respectively).

I tried a solution I found via Google for the string part:

strcpy (new[0].name, old[0].name);
new[0].data = old[0].data;

but I have no idea how to handle the struct. Seems I lack basic understanding of how to handle arrays but I don’t want to learn C – I just need to complete this task.

Answer

If you don’t want to learn C, you should be able to read the old file format in any language with a half-decent IO library.

To complete what you’re trying to do in C, you could use memcpy.

So instead of:

new[0].data = old[0].data;

Use

memcpy(new[0].data, old[0].data, sizeof(foo) * 16);