When I run the following code:
int i[] = {1,2,3};
int* pointer = i;
cout << i << endl;
char c[] = {'a','b','c','\0'};
char* ptr = c;
cout << ptr << endl;
I get this output:
0x28ff1c
abc
Why does the int pointer return the address while the char pointer returns the actual content of the array?
This is due to overload of << operator. For char * it interprets it as null terminated C string. For int pointer, you just get the address.
The operator
cout <<
is overload 'char *' so it knows how to handle it (in this case, printing all chars till the end one).
But for int is not, so it just prints out the 'memory address'
A pointer to char is the same type as a string literal. So for the sake of simplicity, cout will print the content of the char array as if it was a string. So when you are doing this:
cout << "Some text" << endl;
It does not print the address, the same way as your code is doing.
If you want to pring the address, cast it to size_t
cout << reinterpret_cast<size_t>(ptr) << endl;
Related
#include <iostream>
int main()
{
char *p = new char[1024];
std::cin >> p;
char q = *p;
std::cout << "&q = " << (void*)&q << '\n';
return 0;
}
My question is what is the meaning of (void*) in this case and why does it output the address of q but if this snippet looked like this:
std::cout << "&q = " << &q << '\n';
it outputs the character inputted and gibberish after like so: aó√ä²$↔4 where I entered a as the char. Does the usage of (void*) only apply to characters or would I have to use this when I want to output the address of q lets say but its an int or a string.
Thanks
Insertion operator (<<) for std::ostream objects (of which std::cout is one of the examples) has a specific overload for char*/const char* pointers, where it treats them as C-style null-terminated strings (of which &q obviously is not).
For all other pointers (including a void* one), a different overload is used, the one which just prints the pointer's value.
This is not so much a question that I need solving, it's more a case of I made a mistake which resulted in weird output, and I'm curious what's going on.
So if point1 is a pointer to the char "var", and point2 is a pointer to the pointer point1, to correctly dereference point2 as follows:
cout << **point2 << endl;
Which would ouput "y" as expected.
However, if I incorrectly dereference the pointer, as follows:
cout << *point2 << endl;
Then the output would include any subsequent variables declared after the initial variable var.
For example, in the code below, var2 would also be included, for an ouput of "yn", and further variables such as
char var3 = 'a';
char var4 = 'b';
Also seem to be included for an ouput of "ynab".
I think I understand how it's happening, and outputting the memory addresses of each of the variables through a method such as:
cout << (void *) &var <<endl;
Which confirms that each variable is adjacent in memory, however I'm unsure why it is happening.
Why does improperly dereferencing a pointer to a pointer seem to return successive variables?
Code:
#include <stdio.h>
#include <iostream>
using namespace std;
char var = 'y';
char var2 = 'n';
//Declare point1 as a pointer to a char
char* point1 = &var;
//Declare point2 as pointer to pointer to char
char** point2 = &point1;
int main(int argc, char **argv)
{
cout << "Dereference point1: " << *point1 << endl;
cout << "Dereference point2: " << **point2 << endl;
cout << "Bad dereference of point2: " << *point2 << endl;
cout << "Var: " << var << endl;
return 0;
}
The expression *point2 is of type char * which is treated as a string. If it's not really a string then you have undefined behavior and that's really the end of the story.
In reality what happens is that the output operator << reads consecutive bytes from memory until it hits a zero (the "string terminator"). In your case the compiler have put the storage for the variables next to each other, that's why you see both being output in the "string".
C++ thinks that the pointer to char is the beginning of a string. So it tries to continue printing until it finds a NULL value.
void reverse(char * str){
char * end = str;
cout << "str" << str << endl;//ABCDE
cout << "end" << end << endl;//ABCDE
char tmp;
if(str){
while(*end){++end; cout << end << endl;}//ABCDE-->BCDE-->CDE-->DE-->E--> NULL
--end;//end=E
cout <<"--end" << end << endl;
while(str<end){// do swap
tmp = *str;//*str = str[0]
*str++ = *end;//*end = last ele in str[]
*end-- = tmp;
}
}
}
My input is
char test[] = "ABCDE";
cout << test << endl; //ABCDE
reverse(test);
cout << test << endl; //EDCBA
I am feeling not good about the pointer, since c++ primer book says char* pointer to the first element of an array, but when I output the pointer end, it is the content of an array not the address.
Also, reverse(test), I mean to give the address of the first element in an array to the pointer, but it turns out give the whole elements to the pointer.
A char* variable is a pointer to a char. A char[] is an array of char. Now, an array of char can be accessed through a pointer, and for char* it is commonly used for string processing (it's used although for other types, but for char it's much more common).
char test[6] = "ABCDE";
char *start = &test[0]; // will point on A
Accessing the array with the pointer can be done with pointer arithmetic:
char *end = start + 5; // equivalent to char *end = &test[5]
Now when you do:
cout << test;
or
cout << start;
It's actually calling an overload of operator<< that takes a const char*. What this operator does is that it print char starting from the pointer passed until it reaches a null char ('\0').
If you want to print the address contained in the pointer and not the string, you have to cast it to void*:
cout << static_cast<void*>(start);
std::cout is overloaded to print strings for char* .
Try:
char *test = "ABCDE";
std::cout << (void *) test << std::endl;
Consider the following example
I want to print the address of "hello", not of ptr
#include<iostream>
using namespace std;
int main()
{
char *ptr = "HELLO";
cout<<"VALUE OF ptr"<<ptr;
cout<<"ADDRESS OF ptr"<<&ptr;
cout<<"WANT TO PRINT ADDRESS OF STRING HELLO";
return 0;
}
The << operator for most types prints the value of the right operand. The << operator for char* is different in that it prints the string that the char* value points to; it dereferences the pointer, and then traverses the characters of the string, printing each one, until it reaches the terminating '\0' null character.
To print the pointer value rather than what it points to, just convert it to void*, since << for void* prints the actual pointer value:
cout << "The address of the string is " << (void*)ptr << "\n";
or, if you prefer:
cout << "The address of the string is " << static_cast<void*>(ptr) << "\n";
(Incidentally, ptr should be a const char* rather than a char*.
Cast it to any other pointer. (void*)ptr or reinterpret_cast<int*>(ptr) or something.
I'm having some trouble understanding pointers. In the following code, I'm trying print the address of a variable in 2 ways-once using the address operator and then using pointers:
#include<iostream>
using namespace std;
int main (void)
{
int x = 10;
int *int_pointer;
int_pointer = &x;
cout << "x address=" << &x << endl;
cout << "x address w pointer=" << int_pointer << endl;
return 0;
}
x address = 0028FCC4
x address w pointer = 0028FCC4
This works as expected. But when I do the same thing but now using character type variable, I get some trash output:
#include<iostream>
using namespace std;
int main(void)
{
char c = 'Q';
char *char_pointer;
char_pointer = &c;
cout << "address using address operator=" << &c << endl;
cout << "address pointed by pointer=" << char_pointer << endl;
return 0;
}
address using address operator=Q╠╠╠╠£åbªp é
address pointed by pointer=Q╠╠╠╠£åbªp é
I have no idea why this is happening. Thanks in Advance.
The C++ library overloads the << operator for certain types. (char*) is one of them. Cout is trying to print a string, an array of characters terminated by a null character.
Just cast the pointer:
cout << "address pointed by pointer" << ( void* )char_pointer << endl;
or
cout << "address pointed by pointer" << static_cast<void*>(char_pointer) << endl;
The reason it prints out junky stuff is because your char does not have a null terminator which means the program will keep searching for one until, and in the process will print out whatever it finds. The text you see is ASCII but referenced by the address which the ostream is misinterpreting. To get the address held in memory, you could use implicit conversion or a static_cast. I prefer the latter:
cout << "address pointed by pointer=" << static_Cast<void*>(char_pointer) << endl;
Like 2501 said, in different wording, &c, since c is a char, equals a char *, so it's going to try to print until the new line character '\0' that is either implicitly or explicitly put in character arrays going to std::cout so the stream knows where the end of the character array is.
So, yeah use the (void *) like 2501 said.