4

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;

?

Dan Hulme
  • 14,779
  • 3
  • 46
  • 95
shd
  • 1,201
  • 4
  • 17
  • 29

4 Answers4

5

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.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
4

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

It will be flat. I.e. 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.
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
2

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.

Mihai Maruseac
  • 20,967
  • 7
  • 57
  • 109
0

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.

Community
  • 1
  • 1
Slipp D. Thompson
  • 33,165
  • 3
  • 43
  • 43