Skip to content

Instantly share code, notes, and snippets.

@jonathan-beard
Created December 2, 2015 16:39
Show Gist options
  • Save jonathan-beard/73acf6204f745fa17723 to your computer and use it in GitHub Desktop.
Save jonathan-beard/73acf6204f745fa17723 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <cstdlib>
/**
* low level programming question, exp. C/C++ programmer
* should know:
* How are struct and ptr related? How is this
* different if all the named variables in the struct
* are homogeneous in type? How about when the struct
* has many types?
*/
/**
* Selected ref. material:
*
* From C99 §6.7.2.1:
* 12. Each non-bit-field member of a structure or union
* object is aligned in an implementation- defined manner
* appropriate to its type.
*
* 13. Within a structure object, the non-bit-field
* members and the units in which bit-fields reside
* have addresses that increase in the order in which
* they are declared. A pointer to a structure object,
* suitably converted, points to its initial member
* (or if that member is a bit-field, then to the unit
* in which it resides), and vice versa. There may be
* unnamed padding within a structure object, but not
* at its beginning.
*
* C++ Specifics
* ref: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf
*
* One critical way structs deviate from classes in layout:
* 9.2.15. The order of allocation of non-static data members with
* different access control is unspecified (11).
*
* Other similarities with C structs:
* 9.2.18. Two standard-layout struct (Clause 9) types are
* layout-compatible if they have the same number of non-static
* data members and corresponding non-static data members (in
* declaration order) have layout-compatible types (3.9).
*
* 9.2.21. A pointer to a standard-layout struct object, suitably
* converted using a reinterpret_cast, points to its initial member
* (or if that member is a bit-field, then to the unit in which it
* resides) and vice versa. [ Note: There might therefore be unnamed
* padding within a standard-layout struct object, but not at its
* beginning, as necessary to achieve appropriate alignment.
*/
/** make example struct **/
struct foo
{
int a;
int b;
}F = { 2, 3 };
int
main( int argc, char **argv )
{
/**
* NOTE: you probably never want to do this, but
* if you're doing low level work, it can be useful
* at times.
*/
const int * const ptr( reinterpret_cast< int* >( &F ) );
std::cout << ptr[ 0 ] << " - " << ptr[ 1 ] << "\n";
return( EXIT_SUCCESS );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment