Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the address of a pointer

My apologies, I know there are a million questions on pointers, arrays etc. although as basic as this is I just can't seem to find anything pointing (ha ha!) to an answer.

I've got a pointer that is initialised to point to a chunk of memory, I understand that I can access this memory similar to how I would an array:

char *mMem=new char[5000];
cout<<mMem[5]<<endl;

Which is actually:

char *mMem=new char[5000];
cout<<*(mMem+5)<<endl;

What I don't understand though is how to get the address of an element - I'm aware that element isn't quite the right word considering mMem isn't an array - that's if my understanding is correct, can't be too sure though because it seems every site uses whatever words it wants when it comes to pointers and arrays. So, if I have:

char *mMem=new char[5000];
cout<<mMem[5]<<endl;
    or
cout<<*(mMem+5)<<endl;

why does the address of operator not work correctly:

cout<<&mMem[5]<<endl;

Instead of getting the address of the 5th element, I get a print out of the memory block contents from that element onwards. So, why did the address of operator not work as I was expecting and how can I get the address of an element of the memory?

like image 293
R4D4 Avatar asked Jul 22 '11 08:07

R4D4


2 Answers

&mMem[5] is the address of the 5th element. The reason why you get a printout of the memory from there is because they type of &mMem[5] is char*, but strings in legacy C are also of char*, so the << operator simply thinks that you want to print a string from there. I would try casting the pointer to a void* before printing:

cout << static_cast<void*>(&mMem[5]) << endl;

By the way, &mMem[5] and mMem+5 are just the same.

like image 183
Tamás Avatar answered Sep 20 '22 01:09

Tamás


You are getting the address of element 5 as you expect, but the cout print functionality for a char * is to print out the string contents at that memory location, not the pointer value.

Cast the pointer to an int: cout << (int)&mMem[5]; and you should get the address printed.

like image 33
Anders Abel Avatar answered Sep 21 '22 01:09

Anders Abel