简体   繁体   中英

how to assign fixed size array?

in C , i have

struct a {
    int a;
    char b[16];
    int c;
};

How is the memory of instances of struct a , will it be flat with the struct area, or inside struct a there are pointer, for example , will the struct sizeof be 4+16+4 , or 4+4+4 ?

what will happen if i have

struct a A,B;
A->b = B->b;

?

how is the memory of instances of struct a, will it be flat with the struct area, or inside struct a there are pointer

Flat.

The array member is a real array, the size of the struct will be

2*sizeof(int) + 16 (+ padding)

what will happen if i have struct a A,B A->b = B->b

A compilation error. Arrays are not assignable.

will it be flat with the struct area, or inside struct a there are pointer,

It will be flat. Ie the array will be physically inside your struct

what will happen if i have struct a A,B A->b = B->b

structs have nothing to do with this and this will result in a compile error since arrays cannot be assigned to one another, as struct members or not. Use a loop or memcpy .

You can, however, assign the whole struct, and the arrays will be copied

A = B; //the arrays inside will be copied.

Use a for , you cannot assign to arrays (array names cannot be used as lvalues).

for (i = 0 ; i < 16; i++)
    A->b[i] = B->b[i];

As for the size, sizeof will return at least 2 * sizeof(int) + 16 * sizeof(char) . Due to padding you may have higher values.

To answer your title question, you can't in the form you've written it in, but you can with the help of a union:

struct A {
    int a;
    union {
        char b[16];
        struct { char b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15; }
    };
    int c;
};

Now you can assign and use it like this:

const A test = {
    .a = 1,
    .b0 = 'a', .b1 = 'b', .b2 = 'c', .b3 = 'd', .b4 = 'e', .b5 = 'f', .b6 = 'g', .b7 = 'h', .b8 = 'i', .b9 = 'j', .b10 = 'k', .b11 ='l', .b12 ='m', .b13 ='n', .b14 ='o', .b15 = 'p',
    .c = 255
};

printf("The final b is >%c<.\n", test.b[15]); // prints: The final b is >p<.

This works because of the flat layout of a fixed-size array in a struct (that others have mentioned), and because unions (in this case an anonymous union ) let you access the same memory location via differing types with different identifiers. Essentially, you're just setting up a typecast ahead of time here.

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