Address of struct and address of first m (2024)

Address of struct and address of first member variable

cl0ckw0rk (1)

The address of a struct is the same as the address of its first member variable.

1
2
3
4
5
6
7
8
9
10
11
 struct myStruct{ int number; char ch;};int main(){ myStruct mystruct = {8,'a'}; cout << &mystruct << endl; cout << &(mystruct.number) << endl;

This prints out the same address. So far so good. Building on this fact I want to access the first member variable using the address of the struct.
Something like this:

cout << *(&mystruct);

I know this is pointless but it is for the sake of learning. Adding the above line makes the code not compile. I tried casting the pointer to an int pointer like so:

cout << (int *)*(&mystruct);

But I still get an error (error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream}’ and ‘myStruct’))

Given that both the struct and the first member have the same address, how do we access the member from the struct's address, like I am trying to do above?

And how does the compiler differentiate between doing something with the struct vs doing someting with the first member, if they both share the same address?

seeplus (6563)

Do you mean this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>using namespace std;struct myStruct {int number;char ch;};int main(){myStruct mystruct = {8,'a'};cout << &mystruct << endl;cout << &(mystruct.number) << endl;cout << *(int*)&mystruct << endl;}
000000000019FA80000000000019FA808

But only do things like this for learning purposes!

NB. Read code such as L16 from right to left. Get the address of the struct, cast as a pointer to int (first member), then de-reference this int pointer.

Last edited on

salem c (3697)

Start with

cout << mystruct.number;

Then do

cout << *(&mystruct.number);

It's like the * and the & cancel out, getting you back to where you started.


And how does the compiler differentiate between doing something with the struct vs doing someting with the first member, if they both share the same address?

Because they have different types.
&mystruct is a pointer to the whole structure.
&mystruct.number is a pointer to an integer.

jonnin (11399)

the 'struct' is sort of a 'false entity'. Down in the CPU, there is no such thing as a struct.

maybe this will help...

int i{};
uint8_t bytearray[1000];

int * ip = (int*)bytearray;
i += sizeof(int);
double *dp = (double*)(&bytearray[i]);
i+= sizeof(double);
string *sp = (string*)(&bytearray[i]);
...
this is a 'struct', sort of.
the fields are ip, dp, and sp.

this is (very, very roughly) what the compiler is doing when it turns a 'struct' into machine language, though bytearray would just be ram direct memory offsets.

so you can move the 'struct' around by moving 'bytearray' around as a 'group of bytes', but that is just organization, a 'way to look at it'. there is no 'struct' thing in reality, its just a way to say "this many bytes in a block" when talking at the struct level or "this offset from the starting address" when talking about its fields. That is why the struct and first field share an address: its just a different way of looking at the same block of bytes.

at the c++ level, a struct IS a thing, and a tool you can do a lot with. But that is just a syntax that hides what needs to be done to express it. You do not really care about the memory layout details when using a struct, you just use it and let the compiler do the ugly stuff for you.

Last edited on

JLBorges (13770)

> Given that both the struct and the first member have the same address

This is not guaranteed, except for standard layout types
https://en.cppreference.com/w/cpp/named_req/StandardLayoutType

The object representation of standard layout types are as specified by the C language,
in particular:

A pointer to an object of standard-layout class type can be reinterpret_cast to pointer to its first non-static non-bitfield data member (if it has non-static data members) or otherwise any of its base class subobjects (if it has any) (since C++11), and vice versa. In other words, padding is not allowed before the first data member of a standard-layout type. Note that strict aliasing rules still apply to the result of such cast.
https://en.cppreference.com/w/cpp/language/data_members#Standard_layout

Topic archived. No new replies allowed.

Address of struct and address of first m (2024)
Top Articles
Real Gross Domestic Product (Real GDP): How to Calculate It, vs. Nominal
Report: Fireblocks Business Breakdown & Founding Story | Contrary Research
How To Start a Consignment Shop in 12 Steps (2024) - Shopify
Where To Go After Howling Pit Code Vein
Katie Nickolaou Leaving
Drury Inn & Suites Bowling Green
Tiny Tina Deadshot Build
Canya 7 Drawer Dresser
Compare Foods Wilson Nc
Time in Baltimore, Maryland, United States now
Dte Outage Map Woodhaven
Was ist ein Crawler? | Finde es jetzt raus! | OMT-Lexikon
T Mobile Rival Crossword Clue
My Boyfriend Has No Money And I Pay For Everything
Mustangps.instructure
Self-guided tour (for students) – Teaching & Learning Support
AB Solutions Portal | Login
United Dual Complete Providers
How To Delete Bravodate Account
Mission Impossible 7 Showtimes Near Regal Bridgeport Village
‘Accused: Guilty Or Innocent?’: A&E Delivering Up-Close Look At Lives Of Those Accused Of Brutal Crimes
Betonnen afdekplaten (schoorsteenplaten) ter voorkoming van lekkage schoorsteen. - HeBlad
What Happened To Maxwell Laughlin
Bowie Tx Craigslist
Commodore Beach Club Live Cam
Saatva Memory Foam Hybrid mattress review 2024
Understanding Genetics
Putin advierte que si se permite a Ucrania usar misiles de largo alcance, los países de la OTAN estarán en guerra con Rusia - BBC News Mundo
Costco Gas Hours St Cloud Mn
1979 Ford F350 For Sale Craigslist
Wonder Film Wiki
Pronóstico del tiempo de 10 días para San Josecito, Provincia de San José, Costa Rica - The Weather Channel | weather.com
Tottenham Blog Aggregator
Craigslist Texas Killeen
Rund um die SIM-Karte | ALDI TALK
Los Amigos Taquería Kalona Menu
Gerber Federal Credit
Chase Bank Cerca De Mí
Missouri State Highway Patrol Will Utilize Acadis to Improve Curriculum and Testing Management
Directions To The Closest Auto Parts Store
Weather In Allentown-Bethlehem-Easton Metropolitan Area 10 Days
Jammiah Broomfield Ig
Ehc Workspace Login
Tropical Smoothie Address
Zipformsonline Plus Login
St Anthony Hospital Crown Point Visiting Hours
Yosemite Sam Hood Ornament
Paradise leaked: An analysis of offshore data leaks
Erica Mena Net Worth Forbes
Swissport Timecard
Les BABAS EXOTIQUES façon Amaury Guichon
Códigos SWIFT/BIC para bancos de USA
Latest Posts
Article information

Author: Nathanial Hackett

Last Updated:

Views: 5573

Rating: 4.1 / 5 (72 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Nathanial Hackett

Birthday: 1997-10-09

Address: Apt. 935 264 Abshire Canyon, South Nerissachester, NM 01800

Phone: +9752624861224

Job: Forward Technology Assistant

Hobby: Listening to music, Shopping, Vacation, Baton twirling, Flower arranging, Blacksmithing, Do it yourself

Introduction: My name is Nathanial Hackett, I am a lovely, curious, smiling, lively, thoughtful, courageous, lively person who loves writing and wants to share my knowledge and understanding with you.