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

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.

Related

Can someone please explain this output? [duplicate]

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.

char*p() declaration in a class [duplicate]

This question already has answers here:
Does C have a string type? [closed]
(7 answers)
Closed 5 years ago.
Say that in a class student, I had written the following public member function:
char *p()
{ return (name);}
Now, name is actually a datamember(private section) and is a character string. I assume that this means char* can return a string. If I were writing something similar like:
void main()
{ char *s = "GOODLUCK";
cout<<*s;
}
What does *s give me here? I think it's the whole string 's'. Am I correct?
Description below is far from pedantic, but should help you to start digging into pointers:
char *s means, that s is pointer to char. In other words, it is variable, which can store address of area, capable of storing char. BTW I prefer writing char* s (space moved) as more descriptive: s is variable name, char* is variable type.
"GOODLUCK" is an array of 9 chars (the last one is '\0'). All array memebers are always kept one after another in memory, so if you know address of the first member, you can find address of the second, the third and so on. That's why arrays in C++ are handled as address of the first member.
s = "GOODLUCK"; means "store array address (aka address of the first element) into s". So s now points to the first char of "GOODLUCK".
*s means "get data, which variable points at". s points to the first char of string, so *s is simply a G
cout << *s; means "calculate *s and pass it to cout", so it's identical to cout <<'G';
writing cout << s; (note missing asterisk) doesn't pass one char to cout, but passes pointer to char. cout expects pointer to char to be passed only when it represents address of array, not address of single char. cout will print one by one all members of array, so the whole string will be displayed.
Bottom line: char *p() { return (name);} actually returns address of the first char of the name, but address of the first char represents the whole name. Possible further reading

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.

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;

Why can std::cout print a char[]? [duplicate]

This question already has answers here:
cout << with char* argument prints string, not pointer value
(6 answers)
Closed 5 years ago.
Below code prints the entire string. I am confused why its does so.
char test[] = "jeff";
cout<<test<<endl;
The output is "Jeff", I was expecting it to print the value of char array "test", since test is pointer, pointer the first element which is 'J'.
Why is it printing the whole string, when I cout<<test??
Because of operator<< (basic_ostream<charT,traits>& os, const char* s); (#2 "character sequence" in that list) (slightly more technical list). test decays to a pointer, or char*, which then gets printed as a C-string.
It's the exact same reason cout << "Jeff"; works (instead of printing the address of "Jeff").
The first element is 'j', certainly, but a char* isn't meant to represent only one char, but a string of them. cout will keep reading chars til it find the null char, or '\0'. This is implicitly put there when you use a string literal such as "jeff".
To print only the first char, dereference the pointer to get it like cout<<*test<<endl;.
In C++ (as in C), strings are modeled as NUL-terminated character arrays I.e., the last character's ordinal value is 0, in your example it's character with index 4, inserted by the compiler immediately after the last "f" in "jeff". So in many contexts pointers to "char" are assumed to be NUL-terminated; in this case "cout" keeps printing characters until it hits the NUL character at the end, at which point it stops. C++ also has an actual string class, "std::string", that is in many ways superior to char arrays.