ParksideAdrian
ParksideAdrian

Reputation: 37

Pointers in C++, Raw Memory Operations

I have a few different questions about the following snippet of code, an example given by one of my professors.

First off, what is Thing t{8,15}? Is this an array of two integers, 8 and 15? Or is this initializing the x and y values of t (a varialbe of type Thing) to 8, and 15 respectively? Second, What is happening on the line:

std::cout << "n\t = " << place[0] << ", " << place[1];

It looks to me like it is printing the indicies of the variable place, which to my understanding is a pointer to an int, pointing to the integer values at the memory address of t?

Finally, What on earth is happening on this line:

 int y = *( int *)(( char *)& t + 4);

Here I am lost. Please bear with me, learning pointers and memory

Code im dealing with:

struct Thing {
int x , y ;
int* getPlaces () {
    return & x ;
}
};

int main () {

Thing t {8 ,15};
int* place = (int *)& t ;
std :: cout << "\nt = " << place [0] << ", " << place [1];
int y = *( int *)(( char *)& t + 4);
std :: cout << "\nt.y = " << y ;
int* location = t . getPlaces ();
location [0] = 17;
std :: cout << "\nt.x = " << t . x ;

}

Upvotes: 1

Views: 160

Answers (2)

Adrian W
Adrian W

Reputation: 5026

{8,15} is an initializer list. So, Thing t{8,15} is the declaration of a variable t of type Thing initialized with the values 8 and 15. The members are initialized with these values in order of declaration, i.e. x=8 and y=15.

int* place is the declaration of a pointer to an int, but in C/C++, a pointer is always also an array. So, you can write place[0] for the variable pointed to by place, place[1] for the variable immediately following and so on. There is no bounds checking, so be sure to know what you do.

(some_type) is a (C-style) cast. Casts force the following expression to be interpreted in a certain way. In your example, &t takes the address of t. Then this pointer is forced to be interpreted as pointer to a char (essentially meaning that each item is a single byte). I.e. when you add 4 to that pointer, you point 4 bytes past. Next (to the left), this entire thing is interpreted as a pointer to an int. And finally (the * to the very left), the whole thing is dereferenced, yielding whatever was found at that address intepreted as int.

Summary: this example is for learning only. NEVER program like this in a real progam. The code depends on int being 4 bytes and on the capability of the CPU to allow an int on any address. This is not always the case.

Upvotes: 1

code707
code707

Reputation: 1701

Thing t {8 ,15};

it is initializing t. x and y are member of t which are initialized to 8 and 15.

place[0] and place[1] will print 8 and 15 as place is pointed to t in previous line,.

int y = *( int *)(( char *)& t + 4);

t is converted to (char *) and then added 4 and then it is dereferenced after casting to int *. it will print 15.

Upvotes: 1

Related Questions