-1

Let's say I have a char array of size 5 and:

char array[5];
for (int i=0;i<5;i++)
{ 
    scanf>>array[i];
}

And I as a user of this program provide "hello" as an input. Where is the \0 stored as character arrays are null terminating in C++ right? Or am I missing something?

  • 3
    `where is the \0 stored` -- It isn't. You need a six character array to store `hello\0`, but your array is only 5 characters in size. – Robert Harvey Dec 07 '18 at 22:55
  • BTW, the `operator>>` can't be used correctly with with `scanf`, unless `scanf` is derived from `std::istream` or is a class that has `operator>>` defined. – Thomas Matthews Dec 08 '18 at 00:42

1 Answers1

1

Perhaps your are mixing concepts.

  • cin>>is C++ syntax, not C (for C you have to use scanf -or sscanf -, fgets, etc)
  • A proper formatted string in C ends with null \0, but it does not mean that any array of type char has to end with \0.
  • The world "hello" will be stored as:

    char array[0] = 'h';
    char array[1] = 'e';
    char array[2] = 'l';
    char array[3] = 'l';
    char array[4] = 'o';
    char array[5] = '\0';
    

So you will need an array of size=6, being the extra char the null character.

Jose
  • 3,306
  • 1
  • 17
  • 22
  • so a character array is always not null terminating then? It's not the case here right? –  Dec 07 '18 at 23:17
  • An array of type char can (or cannot) end with the null character. A string must end with the null character. – Jose Dec 07 '18 at 23:22
  • I couldn't get your point but a character array is a string, right? –  Dec 07 '18 at 23:24
  • Yes, strings are array of characters terminated by the null character. – Jose Dec 07 '18 at 23:28
  • In C so every character array is a string as there is no string datatype. And If I dynamically allocate a array to get char from user then I won't have to worry about the "\0" right? as there will be no space just like in my question. –  Dec 07 '18 at 23:46
  • A C-style string is always an array of characters terminated by a null, even if read from the user. But an array of characters is not required to be treated as a C-style string (ie, an array of bytes instead), so it does not require a null terminator (but then you have to keep track of how many valid `char`s are in the array). And a C++-style string (`std::string`) does not require a null terminator, either. – Remy Lebeau Dec 08 '18 at 00:39