This question already has an answer here:
How to print the address of char array
(1 answer)
Closed 4 years ago.
#include <iostream>
using namespace std;
int main() {
char* str = "geek";
//why is this not giving base address of str i.e. (int*)str
cout<<&str[0];
//output:
//geek
return 0;
}
I think that printing &str[0] should give address of the 0th element that is same as (int*)str, base address.
Please explain.
&str[0] do give you the address of the first character. However the type of that is char* which is interpreted as a null-terminated string, and the corresponding char* overload of the << operator will be used to print it as a string.
You need to convert the pointer to a more generic type, like void*:
static_cast<void*>(&str[0])
On a very related note, don't forget that &str[0] is exactly equal to plain str.
Also don't forget that in C++ literal strings are really constant literal strings, and so str should be of type char const* (or the more common const char*).
Related
This question already has answers here:
Why in the code "456"+1, output is "56" [duplicate]
(3 answers)
What is the answer when integer added to string constant in C language?
(4 answers)
Closed last year.
cout<<"ccccc"+2;
Output:
ccc
I tried searching for it online and I know it is a very dumb question but couldn't find anything anywhere. Please if someone could help me out.
"ccccc"+2;
"ccccc" decays to the const char * pointer referencing the first character of the string literal "ccccc". When you add 2 to it, the result references the third element of the string literal.
It is the same as:
const char *cptr = "ccccc";
cptr += 2;
cout << cptr;
When you wrote:
cout<<"ccccc"+2;
The following things happen(to note here):
"ccccc" is a string literal. In particular, it is of type const char[6].
Now, this string literal decays to a pointer to const char which is nothing but const char* due to type decay. Note that the decayed const char* that we have now is pointing to the first character of the string literal.
Next, 2 is added to that decayed pointer's value. This means that now, after adding 2, the const char* is pointing to the third character of the string literal.
The suitable overloaded operator<< is called using this const char*. And since this const char* is pointing to the third character of the string literal, you get the output you observe.
This question already has answers here:
cout << with char* argument prints string, not pointer value
(6 answers)
Closed 2 years ago.
I have written a simple C++ code, and its working fine. But I don't know how it is working. I am just replacing "l" with "r" using myfun().
The return type of myfun() is char*. If I am returning &(str[0]), that is, only the address of the first element of the array, then why is it printing the complete string "herloworld"? Please explain what return &(str[0]); is doing.
#include <iostream>
using namespace std;
char* myfun(char str[])
{
str[2] = 'r';
return &(str[0]);
}
int main()
{
char str[] = "helloworld";
char* word;
word = myfun(str);
cout << word;
}
The operator << is overloaded for the type char * such a way that it expects that the used pointer of the type char * points to the first character of a string.
So the operator outputs all characters of the passed string until the zero character '\0' is encountered.
Also pay attention to that arrays used in expressions with rare exceptions are converted to pointers to their first elements.
So this call
word = myfun(str);
is equivalent to
word = myfun( &str[0]);
On the other hand, a function parameter having an array type is implicitly adjusted to pointer to the element type.
So this function declaration
char* myfun(char str[]);
is equivalent to the following declaration
char* myfun(char *str);
The both declarations declare the same one function.
And within the function instead of this return statement
return &(str[0]);
you could write
return str;
Correspondingly in main you could write
cout << myfun(str);
without declaring and using the intermediate pointer word.
This question already has answers here:
C++ Adding String Literal to Char Literal
(8 answers)
Closed 5 years ago.
In case 1 the output is blank when I initialize a string like this:
#include <iostream>
#include<string>
using namespace std;
//CODE 1
int main()
{
string s="hello" + 'c';
cout<<s<<endl;
return 0;
}
but when I write it this way it works fine:
#include <iostream>
#include<string>
using namespace std;
//CODE 2
int main()
{
string s="hello";
char k='c';
s+=k;
cout<<s<<endl;
return 0;
}
Now I am confused as in another question asked on stack overflow it says that there is no difference between string and std::string when namespace std is used, those answers go by saying that -> There is no functionality difference between string and std::string because they're the same type
std::string vs string in c++
whereas the answers provided for this question are pointing differences:
compiler is g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-4)
When you have
string s="hello" + 'c';
It's equal to
string s=("hello" + 'c');
With ASCII encoding it's the same as
string s=("hello" + 99);
which is the same as
string s=(&"hello"[99]);
That is, you get a pointer to the 100:th element of the string "hello", which only have six elements (don't forget the terminator).
Going out of bounds leads to undefined behavior.
Because "string" is not a std::string but a const char*, and a pointer plus a number (a character is "just" a number) uses pointer arithmetic, so after your addition, you'll get a const char* which points possibly to garbage memory after your string literal.
The second example works because in this case, s is a std::string which has a operator += for char and does not use pointer arithmetic.
The codes are not the same. In
string s="hello" + 'c';
"hello" is not a std::string. It is a string literal and has the type of const char[N]. When you add a character to it to the array decays to a pointer and you are doing pointer arithmetic. That arithmetic is going past the end of the string literal so it is undefined behavior.
In order to get the first code to act like the second example you need to make "hello" a string. You can use a user defined literal for std::string like
string s = "hello"s + 'c';
or just use a constructor call like
string s = std::string("hello") + 'c';
The expression "hello" + 'c'; is adding a char type to a const char[6] type, with an obscure result. Formally the first argument decays to a const char* pointer, and c is added to that pointer using the normal rules of pointer arithmetic. The behaviour is probably undefined, since the numeric value of c is, in all encodings I've ever come across, a value greater than 6, so you end up attempting to index an element outside the const char array "hello".
In the second version, you are exploiting the overloaded += operator of the std::string class taking a char as an argument, and the character c is concatenated to that string.
"hello" + 'c' gives a pointer past the end of "hello" (e.g. assuming an ASCII character set, 'c' has the numeric value 99, and "hello" + 99 gives a pointer to a memory location that is 99 characters past the 'h' in "hello").
Using such a pointer to initialise an std::string gives undefined behaviour.
The "CODE 2" works std::string has an operator+=() that accepts a char, and appends it to the end of the string.
This question already has answers here:
Why in the code "456"+1, output is "56" [duplicate]
(3 answers)
Closed 6 years ago.
This is my program! I want to know the reason behind such output.
#include <iostream>
using namespace std;
class A{
public:
void fun(int i){
cout<<"Hello World" + i<<endl;
}
};
int main()
{
A obj1;
obj1.fun(2);
return 0;
}
Expected Output :
Hello World2
Actual Output :
llo World
PS:To print "HelloWorld2", I can also code cout<<"Hello World"<< i
"Hello World" is not std::string, it's a string literal so it's type is const char[]. When adding an integer like you're doing with i here you're actually creating a temporary const char* that first points to the first element of the const char[] which is 'H', then you move it 2 spots (because i is 2) so it points to 'l', then you pass that pointer to cout and thus cout starts printing from 'l'. Doing binary operations on such types is called Pointer Arithmetic.
To get a better understanding using an example char array, your code under the hood is similar to:
const char myHello[] = "Hello World";
const char* pointer = myHello; // make pointer point to the start of `myHello`
pointer += i; // move the pointer i spots
cout<< pointer <<endl; // let cout print out the "string" starting at the character pointed to by the new pointer.
Note that if you try to "move" the pointer too much so that it's pointing to something out of the string and then try to access this pointer you get Undefined Behaviour. Same as how accessing an array out of bounds is UB. Just make sure index < size.
"Hello World" + i doesn't do string concatenation. It does pointer arithmetic.
It takes the address of the c-string literal "Hello World", let's call it a.
And then adds to it a + i. Dereferencing the resulting pointer is undefined behavior when i is larger than the length of the c-string literal.
If it's within bounds, however, you'd get an address inside the literal, which will appear as a suffix when printed. However, since a c-string literal is const, attempting to write into that address is UB again.
Long story short, don't do it.
"Hello World" is compiled to an array of characters and is passed to operator<< as a pointer to those characters. Then you add i to the pointer, which moves the pointer on that many characters.
Pointer Arithmetic.
"Hello World" is a string litteral, pointed to implicitly by a const char*.
Adding an integer i to a pointer will move it i positions forward (or backward if i<0).
Hence the result of "Hello World" + 2 is a const pointer (const char*) indicating the address of the third letter in the string.
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;