A bunch of questions about C++'s cstring

183 Views Asked by At

I have a few questions I would like to clarify about cstrings:

1) Initialization: When declaring an array of characters as follows, does C++ automatically defines it as a cstring? or (as I believe) an array of characters?

char a[10];

In other words, is this an array of characters containing only a null terminator ('\0') or is it an empty array of characters?

2) When working directly on a cstring's indexes (i.e. a[i] = ch+1;), does a cstring automatically takes care of its null terminator, or is it the programmer's responsibility to leave space for it and insert it?

Example code (This is what I believe to be the right answer):

char a[10];
int i = 0;
cin.get(ch);

while(ch != '\n' || i < 9) {
    a[i] = ch;
    counter++;
    cin.get(ch);
}
a[i] = '\0';    //either the last index(9) 
                //or the one right after the
                //last input will be set to '\0'

3) When using the <cstring> library (like strncpy, strncat, etc.), does it take care of the null terminator? Example:

char myCstring[] = "I am a cstring";  //size of 15 (including '\0' at i == 14)
strncpy(myCstring, "I am NOT a string object", 14);

Will this result in the following array?

| I |   | a | m |   | N | O | T |   | a |   | s | t | r | '\0' |
  0   1   2   3   4   5   6   7   8   9  10  11  12   13   14

And lastly:

char myCstring[] = "I am a cstring";  //size of 15 (including '\0' at i == 14)
strncpy(myCstring, "I'ma cstring", 14);

Will this result in the following array?

| I | ' | m | a |   | c | s | t | r  | i | n | g | '\0' |x|x|
  0   1   2   3   4   5   6   7   8    9   10  11   12  13 14

Sorry for the mess.

1

There are 1 best solutions below

7
On BEST ANSWER

1) It is an array of chars which are usually 8bit integers.

2) No, it is treated as an array - everything works exactly the same way as it would for an array of ints.

3) Many people consider strncpy to be unsafe - it does add a '\0' character at the end of the string, but not when the string is truncated, similar to your case. The resulting array would look like so:

| I |   | a | m |   | N | O | T |   | a |   | s | t | r | '\0' |
  0   1   2   3   4   5   6   7   8   9  10  11  12   13   14

The trailing '\0' wouldn't be there if you passed 15 for the size though, it is there only because the function was told the array has ended 1 character short. If you passed sizeof(myCstring) as size, the output would be different:

| I |   | a | m |   | N | O | T |   | a |   | s | t | r | i |
  0   1   2   3   4   5   6   7   8   9  10  11  12   13  14

Notice the lack of a trailing '\0' which can cause a segmentation fault when you try reading the string (but doesn't have to in some cases which makes it harder to debug).

4) Yes, as explained in point 3.