difference between char array and string in cplusplus [duplicate] - c++

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

Related

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.

Intricacies of strcpy_s in C++ [duplicate]

This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
Closed 7 years ago.
I am having a difficult time obtaining the correct size of a string in order to satisfy strcpy_s. For example if I specify
char buffer = {0};
char *str1 = (char*)&buffer;
strcpy_s(str1,sizeof("This is a string\n"),"This is a string\n");
Then it will work as expected. If however I declare the following:
char buffer = {0};
char *str1 = (char*)&buffer;
const char* string1 = "This is a string.....";
strcpy_s(str1, ?????,string1);
If I use anything other than a literal in place of ????? it will fail with a memory exception, for example if I use std:strlen(str1), etc. Any size literal for ???? will work. Of course using a fixed literal is not acceptable.
This is a major re-edit of the original question and I apologise to the people who have answered to date. However none of the the answers below have worked.
"This is a string" is a character array. When you say sizeof(Array)/sizeof(type) it will give the size of the array
When you define the string as const char* then the sizeof(pointer) gives the size allocated for the pointer no the array size
const char* ptr = "This is a string\n";
std::cout<<sizeof("This is a string\n")<<std::endl; //==>18
std::cout<<sizeof(ptr)<<std::endl; //==>4
First of all, the second parameter is the size of the destination buffer, not the size of the source buffer.
so the correct way is:
char str1[100];
strcpy_s(str1, sizeof str1, "Whatever string");
or
int n = 100;
char *str1 = new char[n];
strcpy_s(str1, n, "whatever string");
For an array (first example) sizeof returns the size of the array.
For a pointer (second example) sizeof returns the size of the pointer (which is not what you want)
In your second example, string1 is of type const char*. sizeof will return the size of the pointer, rather than the length of the string literal you are pointing to.
The first example works because a string literal is a const char[], and sizeof will correctly return the length of the string (but with the null terminating character as well). It's only coincidental that this works because char is 1 byte. Do not use sizeof to get string lengths.
To make your second example work, try using std::strlen.

What does below pointer syntax mean [duplicate]

This question already has answers here:
Placement of the asterisk in pointer declarations
(14 answers)
Closed 7 years ago.
Does below code segments mean the same thing or each one has a different meaning
char *data = "blah";
char* data = "blah";
char * data = "blah";
The three are same. The only differences are,
The position of the asterisk and the whitespace around them(which is done according to one's preference)
The string literals "blah" could be stored in the same memory location or different locations. From the C11 standard,
6.4.5 String literals
[...]
It is unspecified whether these arrays are distinct provided their elements have the
appropriate values. If the program attempts to modify such an array, the behavior is
undefined.
All of them are same
char *data = "blah";
char* data = "blah";
char * data = "blah";
char*data = "blah";
All of them are same. They all mean, data is a pointer to type char. The space in between don't make any difference. IMHO, you should have googled/binged that up.
EDIT:: Copied from The Paramagnetic Croissant comment, I think it will help others:: cdecl.org

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[] and char*? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
C - Difference between “char var[]” and “char *var”?
Difference between char a[]=“string”; char *p=“string”;
would someone explain what exactly the difference between char[] and char* is?
for example difference between
char name[] = "earth";
and
char *name = "earth";
thanks
char namea[] = "earth";
char *pname = "earth";
One is an array (the name namea refers to a block of characters).
The other is a pointer to a single character (the name pname refers to a pointer, which just happens to point to the first character of a block of characters).
Although the former will often decay into the latter, that's not always the case. Try doing a sizeof on them both to see what I mean.
The size of the array is, well, the size of the array (six characters, including the terminal null).
The size of the pointer is dependent on your pointer width (4 or 8, or whatever). The size of what pname points to is not the array, but the first character. It will therefore be 1.
You can also move pointers with things like pname++ (unless they're declared constant, with something like char *const pname = ...; of course). You can't move an array name to point to it's second character (namea++;).
(1) char name[] = "earth";
name is an character array having the contents as, 'e','a','r','t','h',0. The storage location of this characters depends on where name[] is declared (typically either stack or data segment).
(2) char *name = "earth";
name is a pointer to a const string. The storage location of "earth" is in read-only memory area.
In C++, this is deprecated and it should be const char *name = "earth";
char name[]= "earth"; creates a mutable array on the stack with the size of 6 with the value earth\0.
char* name = "earth"; defines a pointer to a string constant with the value earth\0.
char[] describes an array of char with a fixed number of elements.
char* describes a pointer to a char, typically followed in memory by a sequence of char's typically terminated by a null char \0
With
char *name = "earth"
you must not modify the contents of name.
Hence
name[2] = 'A';
char* is terminated by a '\0' character while name[] has fixed size.
will cause a segfault.
Initializing the variable takes a huge performance and space penalty
for the array. Only use the array method if you intend on changing the
string, it takes up space in the stack and adds some serious overhead
every time you enter the variable's scope. Use the pointer method
otherwise.