test code:
#include <iostream>
using namespace std;
int main()
{
const char* b="str";
cout << b << endl;
cout << *b << endl;
cout << &b << endl;
cout << *(&b) << endl;
return 0;
}
result:
str
s
0x7ffdf39c27f0
str
I run my code on the web runoob online compiler
Why I get these results? I looked some questions about char*, but not enough for me to understand. Can someone explain that to me? Pictures are best.
I want to know more about it with books or blogs recommended.
By the way, usingchar b[] instead of const char*, I get the same results.
Thanks a lot for all of you.
I just want to know why a char pointer's value is not an address.
I think adress is like 0x7ffdf39c27f0. an memory adress.
But const char* b = "str". b is just str.
And I found that *b is the same as *("str").
So I want to know what happened in the memory? why a char pointer's value is not an address?
To understand what the code outputs, you need to understand that C++ output streams (objects with a type such as std::ostream) and therefore objects (such as std::cout) have a number of overloads of operator<<(). The overload that is called depends on the type of argument provided.
I'll explain your second example, but the explanation for the first example is almost identical.
const char* b="st\0r";
cout << b << endl;
cout << *b << endl;
cout << &b << endl;
cout << *(&b) << endl;
cout << b expands to cout.operator<<(b) where b has type const char *. That overload of the operator function ASSUMES the argument points to (the first character of) a nul terminated string, which is represented in memory as an array of char that ends with a char with value '\0' (zero). The operator function outputs each character it finds until it reaches a '\0' character. The first '\0' found is the one YOU explicitly inserted after the 't', so the output st is produced. The fact that your string has a second '\0' after the 'r' is irrelevant, since the operator function stops at the first one it finds.
cout << *b expands to a call of a different overload of operator<<() that accepts a single char, and outputs that char. *b is the value of the first character in the string represented by b. So the output s is produced.
In cout << &b, &b has type const char ** or (equivalently) char const **. There is no overload of an output stream's operator<<() that accepts a const char **, but there is an overload that accepts a const void *. Since any pointer (other than pointer-to-member or pointers to functions) can be implicitly converted to void *, that conversion is performed (by the compiler), so the overload matches, and is called. That particular overload of the operator<<() prints the address in memory.
The implicit conversion in the third case doesn't happen in the first two cases, since a call that doesn't require an implicit conversion is a better match than a call which does.
In the last statement *(&b) is equivalent to b. This is the case because & is the address-of operator in this code, and the * is the dereference operator (which is the inverse of the address-of operator). So the last statement produces the same output as cout << b.
cout << b << endl;
You are printing the string b
cout << *b << endl;
You are printing the pointer that points to the first character of b., so is the same as:
cout << b[0] << endl;
cout << &b << endl;
&b is the memory address of b, which means the address memory to store b in the computer.
cout << &b << endl;
So, you're printing the memory address of b here. The computer store b in the memory address 0x7ffdf39c27f0, so that's what you get.
cout << *(&b) << endl;
You are printing a pointer that points to the memory of b, so you print the value at the memory address of variable b which is the same as
cout << b << endl;
edit: A pointer contains an address that (usually, it could point at a function, for example) represents the location of an object, and to print a pointer (usually) prints the value of that memory address. Because char * is intimately linked with null-terminated strings, there is a special overload for pointers to characters to print the pointed-at string.
A pointer variable is still a variable and will have an address of its own, so &b results in a pointer to a pointer, a char ** in this case and because it is no longer a char *, cout << &b; prints the address of b, not the address pointed at by b or the string pointed at by b.
Related
int q[10]={0};
cout << q << endl;
cout << &q << endl;
cout << &q[0] << endl;
output is
0x7fffd4d2f860
0x7fffd4d2f860
0x7fffd4d2f860
Now when i do this->
int *r=q; // allowed
int *r=&q[0] // allowed
int *r=&q // not allowed
Why is the third assignment not allowed when it is essentially the same thing?
If you have an array declared like
T a[N];
where T is some type specifier then a pointer to the array will be declared like
T ( *p )[N] = &a;
A general rule is the following. If you have a multidimensional array (including one-dimensional arrays) like for example
T a[N1][N2][N3];
then this declaration you may rewrite like
T ( a[N1] )[N2][N3];
To get a pointer to the first element of the array just substitute the content in the parentheses the following way
T ( *p )[N2][N3] = a;
If you want to get a pointer to the whole array then rewrite the declaration of the array like
T ( a )[N1][N2][N3];
and make the substitution
T ( *p )[N1][N2][N3] = &a;
Compare this with a declaration of a scalar object and a pointer to it.
For example
T obj;
You may rewrite the declaration like
T ( obj );
Now to get a pointer to the object you can write
T ( *p ) = &obj;
Of course in this case the parentheses are redundant and the above declaration is equivalent to
T *p = &obj;
As for this code snippet
int q[10]={0};
cout << q << endl;
cout << &q << endl;
cout << &q[0] << endl;
and its output
0x7fffd4d2f860
0x7fffd4d2f860
0x7fffd4d2f860
then array designators used in expressions with rare exceptions are converted to pointers to their first elements.
So in fact the two expression q and &q[0] in these statements
cout << q << endl;
cout << &q[0] << endl;
are equivalent. On the other hand, the address of the array itself is the address of the memory extent that the array occupies. And in the beginning of the extent there is the first element of the array. So the three expressions give the same result: the address of the extent of memory occupied by the array.
Why is the third assignment not allowed when it is essentially the same thing?
Because The C++ language has a feature called "type safety". There is a type system that helps you keep the logic of your program sound.
One particular rule is that arbitrary pointer types can not be used to initialise pointers of other, incompatible types. In this case, you have a pointer to type int (.i.e. int*) that you try to initalise with an expression of type pointer to type array of 10 int (i.e. int(*)[10]). One type is not implicitly convertible to the other, hence the program is ill-formed.
Then why does cout print same things in all of the three cases?
Because all of the pointers have the same value. The first byte of the first element of the array is the same byte as the first byte of the entire array.
It just so happens that the stream insertion operator handles all pointer types1 exactly the same, so pointers with same value but different type produce the same output.
1 Pointers to character types are an exception. They are treated entirely differently.
Why can't we assign address of array to pointer?
Actually, we can assign address of an array to a pointer. We just cannot assign address of a array (or any other object for that matter) to a pointer of wrong type. We need a pointer to an array in this case:
int (*r)[10] = &q;
You cannot do the third assignment because &q's type is an int (*)[10], which is incompatible with the type of int* r.
The output of cout << &q does not reveal the type of &q. See this documentation link.
q is a fixed-length array. Specifying q by itself in an expression decays into a pointer to the 1st element of q. Thus, q decays to the same pointer value that &q[0] returns. &q, on the other hand, returns the memory address of the q variable itself, and for an array, its 1st element occupies that same memory address.
There is an operator<<(void*) defined for std::ostream, and void* can accept (almost) ANY type of pointer. Since all three of your cout calls resolve to the same memory address, and there is an operator<< that accepts all three types of pointers, that is why all three calls print the same number.
As for your assignments:
q is an int[10], which decays into an int*, which is why int *r=q; works.
&q[0] dereferences q to access its 1st element, which is an int, and then takes the address of that element, producing an int*, which is why int *r=&q[0]; works.
since q is an int[10], &q is an int(*)[10], which DOES NOT decay into an int*, which is why int *r=&q; does not work. You would have to declare r using the correct type:
int (*r)[10] = &q;
The following code demonstrates the differences between arr, &arr and &arr[0] where arr is an array of integers.
#include <iostream>
#include <string_view>
// Reference: https://stackoverflow.com/questions/81870/is-it-possible-to-print-a-variables-type-in-standard-c/56766138#56766138
// Type finding code start
template <typename T>
constexpr auto type_name()
{
std::string_view name, prefix, suffix;
#ifdef __clang__
name = __PRETTY_FUNCTION__;
prefix = "auto type_name() [T = ";
suffix = "]";
#elif defined(__GNUC__)
name = __PRETTY_FUNCTION__;
prefix = "constexpr auto type_name() [with T = ";
suffix = "]";
#elif defined(_MSC_VER)
name = __FUNCSIG__;
prefix = "auto __cdecl type_name<";
suffix = ">(void)";
#endif
name.remove_prefix(prefix.size());
name.remove_suffix(suffix.size());
return name;
}
// Type finding code end
int main()
{
int arr[5] = {1, 2, 3, 4, 5};
std::cout << "Value: " << arr << "\tType: " << type_name<decltype(arr)>() << std::endl;
std::cout << "Value: " << &arr << "\tType: " << type_name<decltype(&arr)>() << std::endl;
std::cout << "Value: " << &arr[0] << "\tType: " << type_name<decltype(&arr[0])>() << std::endl;
return 0;
}
See it in action.
Sample Output:
Value: 0x7ffcdadd22d0 Type: int [5]
Value: 0x7ffcdadd22d0 Type: int (*)[5]
Value: 0x7ffcdadd22d0 Type: int*
While all three are associated with the same memory location, they are of different types.
Reference: Is it possible to print a variable's type in standard C++?
This question already has answers here:
cout << with char* argument prints string, not pointer value
(6 answers)
Closed 5 years ago.
char p;
cout << &p;
This does not print the address of character p. It prints some characters. Why?
char p;
char *q;
q = &p;
cout << q;
Even this does not. Why?
I believe the << operator recognizes it as a string. Casting it to a void* should work:
cout << (void*)&p;
std::basic_ostream has a specialized operator that takes a std::basic_streambuf (which basically is a string (in this case)):
_Myt& operator<<(_Mysb *_Strbuf)
as opposed to the operator that takes any pointer (except char* of course):
_Myt& operator<<(const void *_Val)
This is because the pointer to char has its own overload of <<, which interprets the pointer as a C string.
You can fix your code by adding a cast to void*, which is the overload that prints a pointer:
char p;
cout << (void*)&p << endl;
Demo 1.
Note that the problem happens for char pointer, but not for other kinds of pointers. Say, if you use int instead of char in your declaration, your code would work without a cast:
int p;
cout << &p << endl;
Demo 2.
std::cout will treat a char* as a string. You are basically seeing whatever is contained in memory at the location of your uninitialised pointer - until a terminating null character is encountered. Casting the pointer to a void* should print the actual pointer value if you need to see it
If we declare:
int i;
int *ptr1 = &i;
*ptr1=10;
cout << ptr1;
Here ptr1 will give the address.
But:
char *ptr2;
ptr2="Priyesh";
cout << ptr2;
Here it will give the content of the character pointer.
Why is there such a difference?
operator << is overloaded specially for char pointers - the assumption is that if you try to print a char pointer, you actually want to print the string it points to.
If you want to print it the same way as any other pointer, cast it to void* first:
char *ptr2;
ptr2="Priyesh";
cout << static_cast<void*>(ptr2);
(or cout << (void*)ptr2;)
Because there's an operator<< overload that specifically takes a const char* argument to print it as a string.
This question already has answers here:
cout << with char* argument prints string, not pointer value
(6 answers)
Closed 5 years ago.
char p;
cout << &p;
This does not print the address of character p. It prints some characters. Why?
char p;
char *q;
q = &p;
cout << q;
Even this does not. Why?
I believe the << operator recognizes it as a string. Casting it to a void* should work:
cout << (void*)&p;
std::basic_ostream has a specialized operator that takes a std::basic_streambuf (which basically is a string (in this case)):
_Myt& operator<<(_Mysb *_Strbuf)
as opposed to the operator that takes any pointer (except char* of course):
_Myt& operator<<(const void *_Val)
This is because the pointer to char has its own overload of <<, which interprets the pointer as a C string.
You can fix your code by adding a cast to void*, which is the overload that prints a pointer:
char p;
cout << (void*)&p << endl;
Demo 1.
Note that the problem happens for char pointer, but not for other kinds of pointers. Say, if you use int instead of char in your declaration, your code would work without a cast:
int p;
cout << &p << endl;
Demo 2.
std::cout will treat a char* as a string. You are basically seeing whatever is contained in memory at the location of your uninitialised pointer - until a terminating null character is encountered. Casting the pointer to a void* should print the actual pointer value if you need to see it
I thought I understood pointers, but I think there's a nuance by how they're treated differently that I'm not quite following. When I pass an integer pointer or the address of an integer to showInt, it will print out the same memory address as it would outside the function. However. When I pass the following pointer to showChar;
char* value = "One";
showChar(value);
The address of the first element is different inside the function than it is outside the function. I understand that this is behaviour consistent with passing by value, and that a copy of the pointer is made within the function, however I was under the impression that a copy of a pointer still held the same address. Why is it different when dealing with pointers to char? If the char pointer just stores the address of the first element of the string literal, then why would the pointer in the function not point to the same memory location, but instead point to a new area in memory? That suggests to me that it isn't copying a char pointer, but creating a new char pointer and assigning it the value pointed to by the original pointer. If so, I don't understand why.
I understand that you can access the pointer address in the function by passing a pointer-to-pointer, or a reference-to-pointer instead, but why this is the case still confuses me.
Passing a pointer to char;
void showChar(char* name){
cout << name << endl;
cout << &name << endl;
}
Passing a pointer to int;
void showInt(int* num){
cout << num << endl;
cout << *num << endl;
}
The first line in showChar:
cout << name << endl;
will print the contents behind the pointer name, since the IO streams operators in C++ are overloaded to print char-pointers as text instead of the pointer as a number.
With the second line in this function
cout << &name << endl;
you don't print the pointer address name but instead the pointer (address) of the local variable name (which happens to be of a pointer type). That's taking the reference one time too much. What you want is change the behavior of how operator<<(ostream &, char*) works, namely printing the pointer address instead of printing a C-string.
You can do this by simply converting the pointer before passing it to cout, like this:
void showChar(char* name){
cout << (void*)name << endl;
}
Your showChar and showInt functions are printing different things.
In showChar, this:
cout << &name << endl;
prints the address of name, which is a local variable. In showInt, you don't print the value of # rather you print the value of num, which is an address, but not the address of a local variable.
In showChar, if you want to print value of name as an address, you'll need to convert it to some other pointer type such as void*:
cout << (void*)name << endl;
because the overload of operator<< for char* dereferences the char* pointer and prints the C-style string that it points to.
In more detail:
void showChar(char* name){
cout << name << endl; // prints the contents of the string that
// `name` points to
cout << &name << endl; // prints the address of the local variable `name`
}
void showInt(int* num){
cout << num << endl; // prints the value of the pointer `num`
cout << *num << endl; // prints the value of the `int` object that
// `num` points to
}