views:

410

answers:

3

Hello everyone,

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.

Thanks in advance for your help,

Maya

+3  A: 

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);
Daniel Earwicker
And I guess that would work independent of the struct members' types (eg. if I have uint32_t from stdint)?
Maya123321
It actually was memcpy(new[0].data, old[0].data, sizeof(struct foo) * 16);but it worked, thanks a lot!
Maya123321
You could take the constant away by using sizeof(old[0].data) instead of the explicit calculation (sizeof(element)*number_of_elements). That way it won't silently break if the array is extended in size.
David Rodríguez - dribeas
@dribeas - not a concern here, as the old file format is known to use a certain size, so if the array changes size, the program will be incorrect anyway.
Daniel Earwicker
+1  A: 

You can also wrap the C arrays in a struct. Then copying elements will copy the array automatically.

typedef struct {
    char name[100];
} name_array_t;

struct {
    name_array_t name_struct;
    ...
} x;

struct {
    name_array_t name_struct;
    ... other members ...
} y;

x.name_struct = y.name_struct;
nimrodm
Nice! Thank you too!
Maya123321
A: 

(too obvious solution may be)

As we are dealing with the array, we can not do this kind of operation

new.name = old.name;

so i suppose you have to write a function

void Function (char *name , struct new_format *new ); where you need to assign charecter one by one.

Obviously you will Call like this : Function (old.name , &new)

Amar