Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do data members form a range?

Can I treat consecutive data members of the same type as a range? For example:

struct X
{
    int a, b, c, d, e;
};

X x = {42, 13, 97, 11, 31};

std::sort(&x.a, &x.a + 5);   // kosher?
like image 949
fredoverflow Avatar asked Sep 05 '13 12:09

fredoverflow


3 Answers

No, this is undefined behaviour. You are treating x.a like the first element of an array, which it isn't. May work on some implementations, may raid your fridge too ;)

like image 50
Paul Evans Avatar answered Sep 18 '22 23:09

Paul Evans


Don't do that. Compiler is free to add paddings between structure members(and at the end).

like image 42
Eric Z Avatar answered Sep 21 '22 23:09

Eric Z


If this is really something you want to do, make it an array, vector or similar.

As others have said, the standard makes no guarantees about the members being stored without gaps or otherwise things that cause problems. (And to make matters worse, it will appear to work, until you compile it with a different (version of) compiler, or for another architecture some months or years later, and of course, it won't be easy to figure out what went wrong).

like image 30
Mats Petersson Avatar answered Sep 19 '22 23:09

Mats Petersson