Can someone please explain this output? [duplicate] - c++

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.

Related

understand how char works in c++ [duplicate]

This question already has answers here:
What happened when we do not include '\0' at the end of string in C?
(5 answers)
What is the difference between char s[] and char *s?
(14 answers)
Why do string literals (char*) in C++ have to be constants?
(2 answers)
Closed last year.
I am a C++ newbie. Although many similar questions have been asked and answered, I still find these concepts confusing.
I know
char c='a' // declare a single char c and assign value 'a' to it
char * str = "Test"; // declare a char pointer and pointing content str,
// thus the content can't be modified via point str
char str1[] = "Test"; // declare a char array str1 and assign "Test" to it
// thus str1 owns the data and can modify it
my first question is char * str creates a pointer, how does char * str = "Test"; work? assign a string literal to a pointer? It doesn't make sense to me although it is perfectly legal, I think we can only assign an address to a pointer, however "Test" is a string literal not an address.
Second question is how come the following code prints out "Test" twice in a row?
char str2[] = {'T','e','s','t'}; // is this line legal?
// intializing a char array with initilizer list, seems to be okay to me
cout<<str2<<endl; // prints out "TestTest"
why cout<<str2<<endl; prints out "TestTest"?
char * str = "Test"; is not allowed in C++. A string literal can only be pointed to by a pointer to const. You would need const char * str = "Test";.
If your compiler accepts char * str = "Test"; it is likely outdated. This conversion has not been allowed since C++11 (which came out over 10 years ago).
how does char * str = "Test"; work?
String literals are implicitly convertible to a pointer to the start of the literal. In C++ arrays are implicitly convertible to pointer to their first element. For example int x[10] is implicitly convertible to int*, the conversion results in &(x[0]). This applies to string literals, their type is a const array of characters (const char[]).
how come the following code prints out "Test" twice in a row?
In C++ most features related to character strings assume the string is null terminated, which is implied in string literals. You would need {'T','e','s','t','\0'} to be equivalent to "Test".

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.

char* array's base address in c++ [duplicate]

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*).

Why string literals are allowed to be assigned to pointer of type char * in C++ [duplicate]

This question already has answers here:
how is char * to string literal valid?
(5 answers)
Closed 5 years ago.
Using visual studio, I declared a pointer of type char * and assigned to it a string literal. I then hovered the mouse over the string literal and it displayed its type: (const char [4])"abc".
How is this allowed? it compiles without warnings or errors, whilst assigning to the pointer an array of type const char [] fails, for obvious reasons, with an error message:
a value of type "const char *" cannot be assigned to an entity of type "char *"
So, why is it allowed for string literals?
int main(void)
{
char *p = "abc"; // no error here
const char str[] = "abc";
//p = str; This line generates an error
return 0;
}
EDIT: answer updated to incorporate info from Story Teller's comment.
In the olden days, const didn't exist, and people wrote things like char* p = "abc" all the time. As long as the didn't then do something like p[0] = 'z', their program worked. To remain compatible with such code, some compilers allow string literals to be assigned to non-const pointers if you don't ask the compiler to be super-strict. If you take advantage of this feature, you still should not ACTUALLY modify the string.

How is a const char* not a just a character? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm really confused about this because personally, I come from a java background, and recently began c++. So, I learnt all the basic stuff, like, printing stuff out to the screen and whatnot, and now, I learnt POINTERS. So, the person on youtube (The Cherno's C++ Pointer tutorial This was not the video where he declared the const char*, just the pointer tutorial that I followed.) I've been following was using this following statement to declare what I know as a 'string'.
const char* str = "random text here";
But, how is a char* converted into a string, and its even using the double quotation marks like a string! Also, what does a constant have to do with any of this? If I remove the const from my code it gives me an error. But, I understand what a pointer is. It is a variable that holds the memory address of another variable, so if one was to access that variable directly, they would just have to do *ptrVarName and dereferenced it. But how can a string "like this one" be a memory address?
Wouldn't I have to do something like this?
char[] str = "string here";
and THEN do:
char* stringPointer = *str;
(WARNING: untested code!)
Thanks in advance.
(oh and sorry if this is a really NOOBY question or the question is poorly constructed, I've just started out with c++ and stackoverflow)
EDIT: Ok, so I understand what the char* str means. It means that when you reference *str, it means that you're accessing the first character in memory. Ok, I get it now. But, what does const mean?
const char* str = "random text here";
On the right hand side, the "random text here" defines a string literal which actually is an array of type const char[17] (including the null terminator character). When you assign that array to const char* str it decays to a pointer that points to the first character. You cannot modify the string literal through the pointer because string literals are stored in read-only memory, so the following would be illegal: str[0] = 'x';
char[] str = "string here";
This one is different. It defines the char array str which has the same size as the string literal on the right hand side (const char[12]). The string literal will be copied into the array str, so you will be able to modify str. In this case, it would be legal to write str[0] = 'x';.
If you declare const char* sth ="mystring"
It will place mystring inthe memory and sth pointing to that its work like array but with direct access to memory
These are plain C-strings. A C string is always null terminated. In other words- it has '\0' at the end. So you need only the place in memory where the string starts and you can find when it ends.
For pointer arithmetic these [] brackets are only syntax sugar. str[] is the same as *str and str[1] is the same as *(str+1) only incrementing the pointer by one char (8 bits) and getting the address of the second element.
C doesn't really have strings. A string is an array of characters, terminated by a nul (0). Now arrays and pointers in C are closely linked, and a char * or const char * usually points to a string, but only in the same way as other pointers usually point to arrays. An individual char * might only point to a single character, you have to know from context, just as an int * might point to one integer or an array of integers.
Because strings are handy, there's a special syntactical rule for strings literal. A string literal in quotes becomes a const char * (in fact its type is char * for backwards compatibility). So in this sense, C has strings. But all that is happening is that the string is being laid out in the data section of the program, then its address taken.