Link to home
Start Free TrialLog in
Avatar of Eric Zwar
Eric ZwarFlag for Australia

asked on

C/C++ Display the contents of a pointer

Hi, I am trying to see the actual address that a C/C++ pointer points to.  I can easily see the data that it points to but I'm trying to see the actual address of those data, i.e., the contents of the pointer itself.

I am using cout for the attempted display of this which will be an address in hex (along with other data that displays just fine in my cout statement).

The environment is VS2015.

Any help will be appreciated.
Avatar of David Johnson, CD
David Johnson, CD
Flag of Canada image

// Declaration and assign variable a
int a = 7;
// Declaration pointer b
int* b;
// Assign address of variable a to pointer b
b = &a;

std::cout << "a: " << a << "\n";       // Print value of variable a
std::cout << "&a: " << &a << "\n";     // Print address of variable a

std::cout << "" << "" << "\n";

std::cout << "b: " << b << "\n";       // Print address of variable a
std::cout << "*b: " << *b << "\n";     // Print value of variable a
std::cout << "&b: " << &b << "\n";     // Print address of pointer b

std::cout << "" << "" << "\n";

Open in new window

generally a pointer is a 32-bit or 64-bit variable which can be looked on as an integer. they mostly use unsigned integer in hex notation.

for example

SomeType p = new SomeType();

std:: cout << "pointer address = 0x" << (unsigned int)p << std::endl;

what might give an output like

pointer address = 0x01ab9870

the 0x01ab9870 is the address within the virtual address space the process owns. at  this address the data of SomeType are stored. if SomeType for example is a char and the value is 'A' you would find the 'A' byte directly at address 0x01ab9870. if SomeType is a structure of many members all those (fix-sized) members would be stored contiguously in memory.

Sara
Avatar of Eric Zwar

ASKER

Hi David,

I'm trying to see the contents of pointer b, not its address.

But I appreciate your reply.
OK, here's more re the question.  The context is chapter 6 exercise 10 (extended) from Ivor Horton's book Beginning Visual C++ 2013.

A char array called buffer is established in main and data are added to it (from cin).  buffer is then passed to a function where it is received as char * str.  I want to see the content of the pointer str - I know that it points to buffer and with cout you can see the contents of buffer but I'd like to be able to see buffer's address within str.  

Is this possible?

Please ignore my above comment.
I'm trying to see the contents of pointer b, not its address.

The content of b is the address of a, as shown in David's example:

std::cout << "b: " << b << "\n"; // Print address of variable a

Open in new window


.
Try:

cout << (void*)str << endl;
int main()
{
       char szInput[1024] = { '\0'};     // creates an empty buffer with all bytes set to zero
       std::string strInput;
       std::cout << "Enter Text: ";
       // std::cin is not suitable to be used with char arrays
       // use std::getline instead which would read char input into a std::string after the user typed 'enter' key.
       std::getline(strInput);
       // to copy the input into a char array we use strcpy
       // the std::string::c_str member function returns a constant char pointer to the first char of the input string
       strcpy(szInput, strInput.c_str());   // the copy will end when the terminating zero byte was detected. 
                                                                  // if the input was more than 1023 characters, the statement would write beyond allocation 
       strncpy(szInput, strInput.c_str(), sizeof(szInput)-1);   // this would be safe

       char * psz = szInput;   // a char array can be assigned to a char pointer. 
                                              // it would point to the first byte of the array
                                              // the pointer has no size information 
        char * psz1 = &szInput[0];  // this is equivalent to the statement before
        assert(psz == psz1);              // i. e. psz and psz1 are pointing to the same address

        // get the pointer value as unsigned integer
        unsigned int addr = (unsigned int)psz;    // this is a reinterpret cast of psz 
                                                                                // we see a pointer is an address 
                                                                                 // but the address now can't directly be read as string
         psz1 = (char *)addr;   // with a cast you could get the info back what kind of contents could be found at the address
                                               // note, this is not a good programming and should be avoided (if possible).
         char c = *psz1;    // by dereference you would get the first char of the char array 
         char c1 = *(++psz1);  // this would increment the pointer (address) by 1 and so dereference the 2nd byte
                                              // psz1 now points to the second char
          std::cout << psz1 << std::endl; // if input was "Hello World" the statement prints "ello World";

          char * psz2 = "";    // if we have an empty string the pointer points to terminating zero byte
          char z = *psz2;      // z is a binary 0 
          char x = *(++psz2);  // this is a buggy statement because the contents beyond the terminating zero is undefined

          return 0;
}

Open in new window


Sara
To stop the stream operator overload for pointer types kicking in, just cast the pointer to a size_t, which is an integer type that will be the same size as a pointer. The contents of the pointer (the address it contains) will then just be treated as a normal integer value and you can format it using the standard IO manipulators.

It's worth noting that Sara suggested something similar, above, but that seems to have been overlooked.
Thank you to everyone who is helping.

I tried jcgd's approach and that worked perfectly for my situation.

I will mark this as the solution to my query but I will also check out the other advice that has been given tomorrow and sincerely thank everyone for their interest and suggestions.
And sarabande's example is also very helpful - thank you!
If I may, I have a couple of associated questions.  As can be seen, I am in learning mode here and am striving to get a deeper understanding of how these things work.  So...

1) Can you please help me better understand how jcgd's solution works - i.e., how cout << (void*)str << endl; shows the value of the address that str points to.

2) As per my post above, in main a call is made to let's say function_1passing it buffer as a parameter.  function_1 receives it as char * str which is a pointer to the first character in the char array buffer.  OK, that bit I think I understand OK - another website said that buffer, as a parameter in a call to a function, is received as a constant pointer to non-constant data.  OK.

Then function_1 calls function_2 passing it str as a parameter.  However, in the exercise mentioned above, function_2 receives the pointer value as const char * str  - i.e., with the pointer in function 2 defined as const etc..

I don't understand the subtlety whereby in function_1 str is defined without the const stipulation but in functuion_2 it is.

Any insights will be most appreciated and thanking you in anticipation.
1. The cast stops the stream operator overload for chat * being called, which will always output the string and not the pointer value.

2. When arrays are passed by value to functions, they will always decay to a pointer, which points to the start of the array. That pointer doesn't have to be const, but it can be. Whether the data it points to is const or not depends how the data was initially defined. For example, passing a string literal means the pointer will be pointing to const data. Passing an array containing string data will not (unless originally declared const).
1)  char * is a pointer to a C string ending in null. Therefore cout << prints the string itself.

void * is a pointer to a memory buffer of unknown type, therefore, cout << prints the value of the pointer since it does not know the type of object it points to

2) In C ++ if function 2 expects a constant string pointer as a parameter, then function 1 cannot pass a pointer to a non-constant string because it will give compilation error, unless cast the type in the call: function2((const  char*)str).
SOLUTION
Avatar of Juan Carlos
Juan Carlos
Flag of Peru image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you everyone for your advice.  I understand 1) - the casting OK now.  Re 2) if I change any of the function receiving parameters by either adding or removing a 'const' I get compile errors so I will leave well enough alone with a better understanding of the mechanism, but to be honest not a complete in-depth understanding.  But that's OK.  I will leave it as 'solved' and thanks again.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
All of the experts were helpful so thank you again!
Just out of curiosity, why did you discard my solution?
I did not discard it - that is the one I used - why did you think that I discarded it?
Because you chose another solution.
Evilrix solution
Sorry, that is because I did not understand exactly how this 'solution' system works.  I just chose your solution - does that mess things up?  Hope not!