Does char *a[] ={"yes","no"} requires malloc? [duplicate] - c++

This question already has answers here:
String literals: Where do they go?
(8 answers)
Closed 4 years ago.
statements like: char *a = "hello" or char *b[]= {"yes", "no"} seem to be accessible and printable without any problems in C.
Do they require a malloc?

Case 1 :- char *a = "hello"; Here a is char pointer and it needs valid address and its assigned with valid address as hello is string i.e address. So no need of malloc() here.
Case 2 :- char *b[]= {"yes", "no"}; Here b is array of char pointer i.e each element of b is pointer that means each elements needs to be initialized with valid address and its assigned with valid address as b[0] with yes(i.e address) and b[1] with no(i.e address). So here also no need of malloc().

"hello" here is string constant which is residing in data segment which is readable section of memory.
char *a ="hello" is nothing but you are assigning the address of const string "hello"
to char pointer a.
if you try to modify content of this const string using ptr a it will crash.
e.g
a[1]= 'E' /// -> this is undefined behavior
If you want to own memory then malloc and copy string into memory created using malloc.

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".

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

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.

C Style Strings Difference : C/C++ [duplicate]

This question already has answers here:
What is the difference between char a[] = ?string?; and char *p = ?string?;?
(8 answers)
Closed 9 years ago.
What is the difference between C Style Strings
char str[10]="Hello";
char str[]="Hello";
char* str= "Hello";
1) I believe that char str[10]="Hello" is automatic variable and stored on the stack.True? i.e. Allocates 10 bytes on stack.
2) Does char str[]="Hello"; is also stored on stack? i.e. allocates 6 bytes - including null character on stack.
3) Does char* str= "Hello"; stores pointer str on stack and the object "Hello" is stored on heap? i.e. allocates 6 bytes - including null character on heap.
4) All strings (in question 1,2 and 3) are null terminated . True/False?
5) Whether it is C or C++ whenever we create an string like "Hello" , it is always null terminated. Suppose in C++ we declare string str = "Hello"; , is it also null Terminated?
EDIT
Consider All declared in main().
#Negative points and close requests. I am asking this question with respect to where they are stored heap or stack? And also null termination.
"Consider All declared in main()."
Then
1) Yes.
2) Yes.
3) Yes, and no (it's stored neither on the stack nor in the heap in common implementations). "i.e. allocates 6 bytes" -- you seem to have forgotten about the memory required for the pointer. Also, there's an erroneous claim in the comments and in another answer that char* str= "Hello"; is wrong, but in fact it is legal C and, for now, legal C++ ... see What is the type of string literals in C and C++?
4) True, but it would be false if you changed 10 to 5 -- that is, given char str[5]="Hello";, str is not NUL-terminated.
5) False and no (although the implementation might store a NUL following the string -- C++11 requires it -- but that isn't part of the string).
"I am asking this question with respect to where they are stored heap or stack?"
Where do people get the idea that these are the only sorts of memory? Local variables are stored on the stack and memory allocated via malloc or (non-placement) new is allocated from the heap. Program code, file-scope variables, and literals fall into neither of those categories.
You are looking at this kind of sideways, which is probably why you are confused ;-)
1) If these variables are all declared inside a routine definition, without the static keyword, then they are all on the stack.
BUT char str[10] and char str[] are arrays - you get all characters of the array on the stack.
char *str is a pointer to one or more characters. Only the pointer is sure to be on the stack.
2) "Hello" always represents a NULL terminated string in C - it's 6 char's long. If you wanted to initialize a character array to contain a set of characters which is not NULL terminated, you can't do it this way.
3) As people have pointed out in the comments, it's unclear what char *str = "Hello"; does, or even whether it's legal. If it were char const *str = "Hello"; and the compiler accepted it, I'd expect to find the 6 character string somewhere anonymous, global, and possibly protected.
4) I haven't a clue what the "string" class does in C++.

difference between char array and string in cplusplus [duplicate]

This question already has answers here:
What is the difference between a Character Array and a String?
(10 answers)
Closed 9 years ago.
I want to know the difference between character array and string in c++.
Can any one answer to this??
Please,
Thanks
Vishnukumar
string is a class/object, with methods and encapsulated data.
A char array is simply a contiguous block of memory meant to hold chars.
(1) char array is just a block of char type data:
e.g. char c[100]; // 100 continuous bytes are allotted to c
(2a) By string, if you mean char string then, it's little similar to array but it's allocated in the readonly segment of the memory and should be assigned to a const char*:
e.g. const char *p = "hello"; // "hello" resides in continuous character buffer
[note: char c[] = "hello"; belongs to category (1) and not to (2a)]
(2b) By string if yo umean std::string then, it's a standard library class from header and you may want to refer its documentation or search on web