C++ Pointers - C - Style Strings [duplicate] - c++

This question already has answers here:
pointers and string literals
(3 answers)
Closed 7 years ago.
I am fairly new to C++,when I was reading about pointers I got confused a bit:
char str[] = "Alex"
char *ptr
ptr = str
cout << ptr
This gives "Alex" string itself , rather than the memory location and also, *ptr would give you the letter "A".Would someone explain to me why this is happening please?
Also, in addition to this.When I tried printing
cout << *ptr
it gives me address of 1st character.why is this ?, i was expecting the 1st value instead

operator<< has an overload that takes an ostream (the type of cout) and a const char*.
That overload treats the const char* argument as a null terminated C-string, and prints characters pointed to by that pointer, until it finds the terminating null character.
Note that passing a char pointer that doesn't point to a null terminated sequence of chars invokes undefined behavior.
For circumventing this behavior when you simply want to output the memory address, cast the pointer to void* first:
cout << static_cast<void*>(ptr); // outputs the address stored in 'ptr'

C style strings are just C-style arrays of char, with all the semantics associated to C-style arrays.
iostream is special-cased to behave differently when given a char pointer; if you want to print the address you should cast it to void* first.

it is happen because in c++ you can overload operators, like this:
ostream& operator<<(ostream& os, const char* p)
{
while (*p) cout<<*p++;
}
and because char array is a common type of strings, it was done for you in the standard language.

Because strings in C/C++ ends with '\0'. The output will run to the next pointer until it reaches the pointer wich point to '\0'.
ptr + 0 == 'A';
ptr + 1 == 'l';
ptr + 2 == 'e';
ptr + 3 == 'x';
ptr + 4 == '\0'; // stop, end of output

Related

defining a string in C++ with const char *str="Hello"; [duplicate]

This question already has answers here:
cout << with char* argument prints string, not pointer value
(6 answers)
Closed 2 years ago.
I am a little confused here. In the statement const char *str="Hello";, str is a pointer to a char variable pointing to the first character 'H' of the string "Hello", so str should contain the address of the 'H' character. And yet, if I use cout<<str, it prints the entire string "Hello" and not the address.
And also, If I use cout<<*str to print the value stored in the address pointed to by str, it prints the char 'H' correctly.
Can someone please explain how and why this happens? This may be very basic, but an explanation would help me understand these concepts more clearly.
str is a pointer to a char variable
There is no char variable in the example. str does point to a char object.
Can someone please explain how and why this happens?
Because the binary operator << whose left hand operand is an output sream and right hand operand is a pointer to char is specified to print the entire string.
If the pointed char isn't within an array that contains the null terminator character starting from that character, then the behaviour of the program would be undefined. String literals are null terminated, so the example is correct.

Why does an array of characters in C++ return its items instead of its address? [duplicate]

This question already has answers here:
Printing C++ int pointer vs char pointer
(3 answers)
Closed 3 years ago.
For instance,
const char str[] ={'H','e','l','l','o', '\0'};
const int nums[] = {1,2,3,4,5};
cout << str << " " << nums;
gives:
Hello 0x7ffff85c0cf5
Obviously, if I wanted to get addresses of both, I could do
cout << &str << " " << nums
But I'm wondering why there's a difference between this array of integers and an array of characters (string literal). Is this a special case preserved only for strings?
Yes you're absolutely correct. The << operator on ostream has a special overload for a const char*.
There's no such overload provided for an int* - in that case the const void* overload is picked.
There is an overloaded operator<< for const char*, which your const char[] array decays to. This overload treats the char data as a null-terminated string, printing out characters until a null character is reached. However, your char[] array does not have a null terminator in it. You are lucky you are seeing only Hello and not extra garbage, or crashing the app. Your code has undefined behavior because of this.
There is no overload of operator<< for a const int[] array. Your array decays to const int*, which is handled by the operator<< overload that takes a const void* as input, which prints out the address being pointed at.

In char x[10]="hello" , why cout<<x; doesn't print out the array's address? [duplicate]

This question already has answers here:
Why does cout print char arrays differently from other arrays?
(4 answers)
Closed 6 years ago.
As in
int x[3] = {1, 2, 3, 4};
cout<<x;
would print out x address. But if I choose character array, like
char x[10]="Hello";
it prints out the string
Hello
And let's say compiler is smart enough to understand that in case of char array , it is point less to print out address and so it prints out the string instead, then how do I print char array address?
And consider this statement
char *ptr = "hello";
Why is this legal, Aren't pointers supposed to store only address?
It prints "Hello" because operator << has an overload for const char* (which is what you're passing if you pass x) that prints out a single char and moves to the next char until a NUL-character is found. "Hello" has a compiled-added NUL-character at the end, so your string is actually "Hello\0".
To get the address you can cast it to a void* to remove the overload of const char*:
reinterpret_cast<const void*>(x)
Why is this legal, Aren't pointers supposed to store only address?
Yes, that's exactly what ptr is storing. When you assign a pointer to "Hello" which is a const char[] the ptr will point to [0] of that array. Note though that in this case a conversion first has to be made from const char* to char* which has been deprecated for years and is since C++11 illegal because trying to edit the pointee through this char* will lead to undefined behaviour. Some compilers still allow this though while really they should emit an error.

The value of the pointer to char address [duplicate]

This question already has answers here:
cout << with char* argument prints string, not pointer value
(6 answers)
Closed 7 years ago.
In VS C++ I have a simple declaration of a char variable and a pointer to char.
char mychar = 'c';
char *mypointer = &mychar;
When printing the value of mypointer using cout I would expect an 8 character address value like 0038FEDC to appear in console. Instead I am getting some strange results like:
c│■8, ck∙<, c;■8 etc...
Why these strange characters appear when outputting pointer to char values?
std::ostream, of which std::cout is an instance, has an overload for operator<< which treats char* as a pointer to the first character in a null-terminated string.
You are passing it a pointer of a single character, not a null terminated string. This causes undefined behaviour.
In practice what is likely to happen is that a stream of characters will be printed out by treating the memory starting from mychar as an array of char and iterating over it, until a \0 is found.
If you want to print the address, you can cast the pointer to something that isn't char*:
std::cout << static_cast<void*>(mypointer) << std::endl;

can not print address of a pointer in c++ [duplicate]

This question already has answers here:
C++ return string keeps getting junk
(1 answer)
ostream cout and char *
(3 answers)
Closed 8 years ago.
I'm new in c++. I wrote this program.
#include <iostream>
using namespace std;
int main(void) {
int x=24;
char y='A';
char* pchar=&y;
int* pint=&x;
cout <<"pchar= "<<hex<<&pchar<<endl;
cout <<"pint = "<<hex<<&pint<<endl;
cout <<endl;
cout <<"pchar= "<<hex<<pchar<<endl;
cout <<"pint = "<<hex<<pint<<endl;
pchar=NULL;
pint=NULL;
getchar();
return 0;
}
and its result
Can you help me to understand why I can't print the address of variables without &?
I think pchar is already the address of y.
thanks
When you use a char* (like your variable pchar) the string overload of operator<< function is used, and when treating it as a string it will print characters until it find the string terminator character ('\0'). Unfortunately in this case pchar points only to a single character, so you have undefined behavior as the function goes out looking for characters in memory not allocated to you.
To print a pointer you have to cast it to void*:
std::cout << "pchar = " << std::hex << reinterpret_cast<void*>(pchar) << '\n';
It works when you print the address of the variable pchar (when you print &pchar) because then the type of the expression is of type char** which have no direct overload, and instead uses the generic pointer overload (case 7 in this reference).
Operator << treated char* as a string. But you can change your code to following
cout <<"pchar= "<<hex<<(void*)pchar<<endl;
It should work.
I cannot access std code now, but cout implementation should contain something like this
operator << (char* char_ptr)
{
//interpret char * as pointer to null-terminated string
... code to output string
}
So there is impossible to print char* as address without casting to something.
You'll need
cout <<"pchar= "<<hex<<static_cast<void*>(pchar)<<endl;
to print the value of pchar (not its address, that would be the address of the variable pchar, not the address to which it points to).
It behaves like this because std::ostream (cout's type) has an overloaded operator<< which takes a char* and treats it specifically to print out a string.
Change this statement
cout <<"pchar= "<<hex<<pchar<<endl;
to
cout <<"pchar= "<<hex<< ( const void * )pchar<<endl;
The problem is that when you write this way
cout <<"pchar= "<<hex<<pchar<<endl;
the compiler considers pchar as an address of the first element of a string and tries to output this string. There is an overloaded operator << for type char * and it is called in this case.
pchar value is address of y. So if you print pchar it will print address of y. &pchar, it will print address of pchar. Remember pchar also have some address.