Fennekin
Fennekin

Reputation: 216

Are elements stored in struct are next each other

if i have a struct , say:

struct A {
int a,b,c,d,e;
}
A m;//struct if 5 ints
int n[5];//array of 5 ints.

i know that elements in the array are stored one after other so we can use *(n+i) or n[i]
But in case of struct ,is each element is stored next to each other (in the struct A)?

Upvotes: 2

Views: 2122

Answers (4)

Emilio Garavaglia
Emilio Garavaglia

Reputation: 20730

The only thing that is granted is that members are stored in the same order. Between elements there can be some "padding" the compiler may insert so that each value is aligned with the processor word length.

Different compiler can make different choices also depending on the target platform and can be forced to keep a given alignment by option switches or pragma-s.

Your particular case is "luky" for the most of compiler since int is normally implemented as "the integral that better fits the integer arithmetic of the processor". With this idea, a sequence of int-s is aligned by definition. But that may not be the case, for example if you have

struct test
{
   char a;
   short b;
   long c;
   long long d;
};

You can dscovery that (&a)+1 != &b and (&b)+1 != &c or (&b)-1 != &a etc. What is granted is the progression &a < &b; &b < &c; &c < &d;

Upvotes: 4

Tasos Vogiatzoglou
Tasos Vogiatzoglou

Reputation: 2453

Structs members in general are stored in increasing addresses but they are not guaranteed to be contiguous.so elements may not always be contiguous. In the example above, given $base is the base address of the struct the layout will be the following.

  1. a will be stored at $base+0
  2. b will be stored at $base+4
  3. c will be stored at $base+8 ... etc

You can see the typical alignment values at http://en.wikipedia.org/wiki/Data_structure_alignment#Typical_alignment_of_C_structs_on_x86

Upvotes: 3

Pranit Kothari
Pranit Kothari

Reputation: 9841

I have written simple program to show strut elements are next to each other

int main() {

    struct S {
        int a;
        int b;
        int c;
    };

    S s = {1,2,3};

    int* p = reinterpret_cast <int *> (&s);

    cout<<p[0]<<" "<<p[1]<<" "<<p[2];

    return 0;
}

Output : 1,2,3

Remember, [] or *(i+1) are symantic construct, that suits with pointers, not with struct variables directly.

As suggested in Cheers and hth. - Alf's answer, there can be padding, before or after struct elements.

Upvotes: -1

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145269

The compiler may insert padding as it wishes, except before the first item.

In C++03 you were guaranteed increasing addresses of items between access specifiers.

I'm not sure if the access specifier restriction is still there in C++11.

Upvotes: 7

Related Questions