How to assign an array of fixed size?

in C, i

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

Like the memory of instances of struct a , will it be flat with the region of the structure, or is there a pointer inside struct a , for example, the size of the structure will be 4 + 16 + 4 or 4 + 4 +4?

what happens if i have

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

?

+4
source share
4 answers

like the memory of instances of struct a, whether it is flat with the region of the structure or inside struct a there is a pointer

Flat.

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

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

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

Compilation error. Arrays cannot be assigned.

+4
source

whether it is flat with the region of the structure or inside struct a there is a pointer,

It will be flat. That is, the array will be physically located inside your structure

what happens if i have structure A, B A-> b = B-> b

structs have nothing to do with this, and this will lead to a compilation error, since arrays cannot be assigned to each other as members of the structure or not. Use a loop or memcpy .

However, you can assign the whole structure and the arrays will be copied

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

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

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

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

+2
source

To answer your question with a heading, you cannot in the form in which you entered it, but you can using the 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 as follows:

 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 the structure (which others mentioned) and because unions (in this case an anonymous union ) allow you to access the same memory location through different types with different identifiers. Basically, you just set a predefined type.

0
source

All Articles