Cout Not Printing Contents of Pointed To Memory - c++

I have the following code:
if (myFile.is_open()) {
int i = 0;
while (myFile.good()) {
char *ptr = &(reinterpret_cast<char*>(&mem[0]))[i];
myFile.read(ptr, sizeof(struct req));
cout << ptr << endl;
i += sizeof(struct req);
}
}
The cout in the loop here seems to print nothing, although I know that the code is definitely setting the memory because it prints out the correct values if I do something like cout << mem[5] instead. Basically, I just want to print the contents of whatever ptr is referring to. This is probably a silly question, but anyone know what's wrong here?

cout << ptr, if ptr is of type char*, treats ptr as a pointer to (the first character of) a C-style string, and it prints the contents of that string up to, but not including, the terminating '\0' null character.
If you want to print the pointer value, convert to void*:
cout << (void*)ptr << ...
That's assuming you actuallly want to print the value of the pointer, which will probably appear as a hexadecimal memory address. Your title says "Contents of Pointer", which would be the memory address (the contents of the pointer object itself). If instead you want to print the data that the pointer points to, please update your question to make it clearer just what you want to print and in what format.

cout << ptr will print ptr as if it pointed to a C string. Thus, if it hits a NUL character, it will stop. For example, if you try cout << "hello\0world", you will only see hello appear.
Consider writing a hexdump of the memory region instead if you want to see its contents.

Related

difference between printf() and std::cout with respect to pointers

I am new to pointers and i cant figure out one simple thing.
int main ()
{
char *str1="pointer";
printf("%p \n", str1);
cout << str1<<endl;
return 0;
}
The output is as follows :
0000000000409001
pointer
Could someone please explain me the difference here.
why isnt cout printing the memory address ? how can i make cout print the address of str1?
The format specifier %p prints a void *, (untrue: so the char * is implicitly converted to void *) the char * is converted to void * before printing. (But this is actually undefined behavior, see comments. The correct way to do that would be printf("%p", (void *) str1);) The corresponding C++ code would be std::cout << (void *) str1 << '\n';.
The code std::cout << str1; prints str1 as null terminated string. The corresponding C-code would be printf('%s', str1);
A pointer is an address to a location in memory.
"pointer" is a C-string in memory, 8 bytes for the letters and a terminating NULL byte. str1 is a pointer to the byte of the first letter 'p'.
printf("%p", str1) prints the value of the pointer itself, that is the memory address (in this case 0000000000409001).
printf("%s", str1) would print pointer, the content of the C-string at location str1.
cout << str1 << endl also prints the content of the C-string. This is the default behavior for pointer of type char* because they are usually strings.
cout << static_cast<void*>(str1) << endl would print the address of the pointer again.
a char* is a pointer to the beginning of an array of characters.
cout "recognizes" a char* and treats it like a string.
You are explicitly telling printf() to print out the decimal representation of a pointer address with the %p formatter.
You are explicitly telling printf() to print out a representation of the pointer address with the %p formatter.
EDIT: edited for accuracy based on comment

Printing out the value of pointer to the first index of an char array

I'm new to C++ and is trying to learn the concept of pointer. When I tried to print out the value of pStart, I was expecting its value to be the address of text[0] in hexdecimal (e.g. something like 0x7fff509c5a88). However, the actual value printed out is abcdef.
Could someone explain it to me why this is the case? What parts am I missing?
char text[] = "abcdef";
char *pStart = &text[0];
cout << "value of pStart: " << pStart << endl;
Iostreams provide an overload that assumes a pointer to char points to a NUL-terminated (C-style) string, and prints out the string it points to.
To get the address itself to print out, cast it to a pointer to void instead:
cout << "value of pStsart: " << (void *)pStart << "\n";
Note that you don't really need pStart here at all though. The name of an array (usually, including this case) evaluates to the address of the beginning of the array, so you can just print it directly:
cout << "address of text: " << (void *)text << "\n";
Get out of the habit of using endl as well. It does things you almost certainly don't realize and almost never want.

C++ - Can't print target of a char pointer

I have a method in C++ that receives a char * data as a parameter, like this:
bool Whatever::method(char * data) { ... }
Now, I want to print the contents of that array. If I try:
for (int i = 0...) {
cout << *(data+i) << endl;
}
it will only print blank spaces. No garbage, just blanks. But if I cast to int * and then dereference, it kind of works (but of course it prints the values as integers):
for (int i = 0...) {
cout << *(int*)(data+i) << endl;
}
What am I doing wrong here? Thanks!
Edit:
The contents of the array are the following:
An enum
A char[6]
A long
What I get is a blank space per char. Even if I remove the for loop and try something like cout << *data << endl; (which should print the first character) it will still print a blank.
I understand that the long won't be correctly printed if I interpret it as a char, and the enum is just a number after all, but anyway I should be able to interpret them as characters... Please correct me if I'm wrong.
The expression
*(int*)(data+i)
casts the char* pointer formed by data+i to int*, and dereferences. This would access sizeof(int) char-values as an int, except that it's Undefined Behavior so it might really do anything. In particular at the end of the array.
If you're interested in outputting the numerical values, instead do
+data[i]
which promotes the char value to int.

C++ address handling (pointers)

I need to track my current location in a data buffer (which will be used as a packet), so I am using two variables, bufferLoc and dataBuffer.
char dataBuffer[8192];
char** bufferLoc;
I am pointing to the starting location of dataBuffer with bufferLoc. But incrementing bufferLoc does not affect its physical address in memory.
bufferLoc = (char**)&dataBuffer;
cout << &bufferLoc << endl;
bufferLoc++;
cout << &bufferLoc << endl;
These two prints will output the same location. Does my error have to do with type casting, with bufferLoc itself, or something completely different?
Thanks for your help.
If your intention is to scan through dataBuffer one byte at a time, then the second variable should be a pointer, not a pointer to a pointer.
char* bufferLoc;
then print it out without the ampersand:
cout << (unsigned int *)bufferLoc << endl;
note that cout will try to print your variable as text unless you cast to an unsigned int*
cout << &bufferLoc << endl;
prints the address of bufferLoc. This address is always the same. You can print the value stored in bufferLoc:
cout << bufferLoc << endl;
this value is the address of dataBuffer initially, when you increment it, it will be 4 bytes greater in the second print statement.
dataBuffer itself stores a pointer to a char array of 8192 bytes. What you want to do is to get this value:
char *bufferLoc = dataBuffer;
and increment this value. Note that type of bufferLoc is a pointer to a char array (just as dataBuffer). After assigning the address stored in dataBuffer to bufferLoc, you can print the first element: like this: cout << bufferLoc[0] << end.

C++: Pointers outputs confusing me

So I have the following code:
cout << _userLoginName << endl;
cout << *_userLoginName << endl;
cout << (_userLoginName+1) << endl;
cout << *(_userLoginName+1) << endl;
the variable char * _userLoginName has been set equal to "smith". My question is simple: Why in the last lines of code do I get the following output?
smith // as from cout << _userLoginName << endl;
s // as from cout << *_userLoginName << endl;
mith // cout << (_userLoginName+1) << endl;
m // cout << *(_userLoginName+1) << endl;
I really did try reasoning the result but I cannot figure it out.
Thank you.
If you give cout1 a char *, it will try to print a string. If you give it a char, then it will print that single character.
_userLoginName and (_userLoginName+1) are of type char *; *_userLoginName and *(_userLoginName+1) are of type char.
1. Technically, "give std::operator<<(std::ostream &, T)".
Pull out a sheet of paper and draw a box with six cell with "smith" written into them:
+-+-+-+-+-+--+
|s|m|i|t|h|\0|
+-+-+-+-+-+--+
^ ^
| +- _userLoginName + 1
+- _userLoginName
Use your pen as your pointer '_userLoginName' and point it at the first cell. Derefencing the pointer (i.e. using *ptr for a pointer ptr) means looking at the content of the cell it points at. That is '*_userLoginName' shows into the content of the cell. Writing a pointer of type char* or char const* does something funny: it follows the pointer and writes the content of each cell it finds until it reaches a cell having the value \0.
This should explain the first to outputs. Now, ptr + 1 looks at the cell next to ptr, i.e. ptr + 1 is another pointer (pull out another pen if necessary) placed the next cell. It does just the same as above.
Consider the type of *_userLoginName—it is char.
Maybe you overlooked that * in this context dereferences the pointer?
Dereferencing a pointer (such as *_userLoginName) always returns the element the pointer is pointing at, in the case of a normal string the first character therein, which is then printed.
Adding n to a pointer (such as _userLoginName+1) increments the pointer by n steps, so if it pointed to the 0th element it will afterwards point to the nth element.
Combine the two to explain the fourth line.
The first cout is looking at the pointer userLoginName (char* and char[] are very very similar in c++). The cout will print all values in memory, treating them as chars, until it comes across a '\0' character, which terminates the string.
The second cout is looking at one memory element, that pointed to by userLoginName, or userLoginName[0].
The third cout is doing the same as the first, but the memory address starts 1 char later than userLoginName, as the pointer is of type char.
The final cout is the same as the second, but is userLoginName[1].
There are two separate overloads for operator<< at work here: One for char-pointers, and one for chars. The second one, for single characters, simply prints that one character. The first one, for char pointers, treats the pointer as the pointer to the first character in a null-terminated array of characters (a "string") and prints all those.
Combine this with the language syntax that a[i] is the same as *(a + i) for an array a, and you have:
cout << s; // prints all characters, starting at the first
cout << *s; // prints only the first character, equal to "cout << s[0];"
cout << s + 1; // prints all characters, starting at the second
cout << *(s+1); // prints only the second character, equal to "cout << s[1];"