简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM