开发者

Getting the address of a pointer

My apologies, I know there are a million questi开发者_运维技巧ons 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜