vow
vow

Reputation: 347

struct copy in c where struct are elements

Hi i have following situation

typedef struct
{
    int a;
    Name team[5];
    Sport sport[5];
} School;

where Name and Sport are also structs,

typedef struct
{
    char arry[20];
}Name;

typedef struct
{
        char arry[20];
        int tag;
}Sport;

then

School first_school, second_school;

I populate them individually, then at some point I do

first_school = second_school

But I step through code this line doesn't seem to work. How should I copy ?

Upvotes: 0

Views: 177

Answers (3)

tdao
tdao

Reputation: 17668

But I step through code this line doesn't seem to work. How should I copy ?

It's entirely correct to copy struct like that

first_school = second_school; // valid

If it doesn't work as expected then the error is somewhere else. For example, you need to do strcpy() for string members.

Upvotes: 2

unwind
unwind

Reputation: 399833

Structures are values that can be assigned. They can contain arrays, which by themselves are not assignable, but being inside a struct makes it possible.

That code is fine, except you need to reverse the order of the declarations, since School references Name and Sport they must be declared first.

I tested it and it works just fine after reversing the declaration order, this prints hello:

int main(void) {
    School foo, bar;
    strcpy(bar.team[0].arry, "hello");
    foo = bar;
    printf("'%s'\n", foo.team[0].arry);
    return 0;
}

There is probably something else wrong with your initialization of the second_shool, or you're failing to verify that it worked.

Upvotes: 1

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

It will work for most members, but you have one that cannot be copied like that arry. You should copy one element at a time from the target to the destination instances.

Note that there are functions that take care of such copying like memcpy(). But you cannot copy an array by assignment like you do with an int or a struct actually.

Upvotes: -2

Related Questions