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?
&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.