Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storage of variables in memory

If I have a list of global variables like this...

int a;
char b;
float c[10];
double d[3];

and I have an identical sequence of variables listed inside a class...

class test_type
{
    int a;
    char b;
    float c[10];
    double d[3];
}

is it guaranteed that the arrangement of all the variables in memory are identical. i.e. is 'b' guaranteed to be stored immediately after 'a' in both the globals list and the class list?

EDIT: I ask because I wanted to A) copy the data from one to the other as a "job lot" and B) I wanted to check for any differences between them as a job lot. If the answer to the main question is "no" then does anyone have any suggestions as to how I get round the problem, preferably leaving existing code as unaltered as possible.

like image 851
Mick Avatar asked Dec 07 '22 06:12

Mick


2 Answers

No. I don't think the C++ standard guarantees anything about the memory layout of global variables.

like image 99
JesperE Avatar answered Dec 31 '22 15:12

JesperE


Why don't you simply use a global object of type test_type instead of defining multiple global variables?

class test_type
{
    int a;
    char b;
    float c[10];
    double d[3];
};

test_type global;

Now, it's a piece of cake to initialize a new test_type object with a copy of "global".

like image 40
sellibitze Avatar answered Dec 31 '22 16:12

sellibitze