简体   繁体   中英

If I have a character array in C++, how does this work?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM