I am trying to cin a value to the birthMonth variable in my structure. My understanding is that structure members are stored sequentially. If that is the case, I cannot find out why using the line
cin >> *((short*)((people) + sizeof(Person::name)));
does not store the input value into the structure element. Am I wrong about the members of a structure being stored sequentially?
main.cpp
#include <iostream>
using namespace std;
struct Person {
char name[15];
short birthMonth;
};
int main() {
Person people[2];
cout << "Birth Month: ";
cin >> *((short*)(people + sizeof(Person::name)));
cout << people[0].birthMonth;
}
Sample Run:
Birth Month: 7
0
Program ended with exit code: 0
Because of memory alignment and padding, C++ actually doesn't give any guarantee that a struct's member is located according to the cumulative size of previous members. If you're trying to write to the first Person
's birthMonth
, it's as simple as:
cin >> people[0].birthMonth;
EDIT: to actually address the question's title, if you want an int*
pointer to a specific person's birthMonth
, it's done using the address-of operator:
int* birthMonth_ptr = &people[0].birthMonth;
But if you want a pointer to any Person
's birthMonth
member, you can use a pointer-to-member :
// Note that no Person object is used when defining
int Person::*member_ptr = &Person::birthMonth;
// To use the pointer though, you need an object
int a_persons_birthdate = people[0].*member_ptr;
Also note that a pointer-to-member is typed differently from a regular pointer, and can't be cast to one.
To understand why your code does not work, add a few lines to print couple of addresses.
short* ptr1 = (short*)(people + sizeof(Person::name));
short* ptr2 = &(people[0].birthMonth);
std::cout << "ptr1: " << ptr1 << ", ptr2: " << ptr2 << std::endl;
You will notice that due to alignment requirements, ptr1
and ptr2
are different.
Further reading: https://en.wikipedia.org/wiki/Data_structure_alignment .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.