I try to use the get-address operator "&" to get the addresses of some member variables of struct type demo.
But strange thing happens if the member type is char.
I don't know what's happening. Can anyone help me and explain why? here is my code:
#include <iostream>
using namespace std;
struct demo{
int a;
float b;
char c;
char d;
char e;
};
int main(){
demo s;
s.a = 0;
s.b = 0.1;
s.c = 'c';
s.d = 'd';
s.e = 'e';
cout << "address of a:[" <<&s.a <<"]"<< endl;
cout << "address of b:[" <<&s.b <<"]"<< endl;
cout << "address of c:[" <<&s.c <<"]"<< endl;
}
I compiled the code with g++ and got the following output:
address of a:[0x7fff96b9f5c0]
address of b:[0x7fff96b9f5c4]
address of c:[cde]
The addresses of s.a and s.b are correctly printed. But why the address of s.c is [cde]? It seems that when the type is char, &s.c returns some values in(may be near)that memory address. Dose it has something to do with memory alignment in structs ?