Character arrays vs c-strings

Hi All,
I have a huge confusion when it comes to character arrays vs cstrings vs String objects(c++).

However I think that

Unless and until I declare an array like this

char arr[10]={'C','O','D','E'};
Compiler will always places NULL implicitly and makes it a null terrminated array or string.

Few Instances when compiler places NULL character imlicitly at the end of array:

1
2
3
char arr[10]="CODE" will be null terminated
char arr[10]; \\If I read arr from buffer then also compiler will add NULL at the end
cin>>arr;    



Operations with strings are always safe and easy because string implementation takes care of all these issues(like placing NULL at the end every time.)


Am i right? Please help here If I am wrong.

You are correct.
char arr[10]={'C','O','D','E'}; Is not null terminated character array.
char arr[10]="CODE" Is a null-terminated character array aka c-string
std::string arr = "CODE"; Is a C++ string class instance created using string(const char*) constructor

There is some other cases when trailing zero might or might be not written, you should check documentaion for that. (strncpy for example)

Operations with strings are always safe and easy because string implementation takes care of all these issues(like placing NULL at the end every time.)
They are more safe. You still can mess up things if you try hard enough.
Last edited on
A c-string is a null terminated character array.

All string literals are null terminated and that's why "CODE" gives you a null terminated array.

Doing cin>>arr; will place a null termination character at the end but it's not very safe. Operator >> doesn't know the size of the array so if the user enter a string that is too big it will write outside the array and maybe overwriting other stuff which could make the program to act weird or even crash. Using std::string in this situation is much safer because the string will automatically resize if needed.
Last edited on
Thanks all
Topic archived. No new replies allowed.