0

There is a saying when we declare char variable.

We should declare like this -> char ArrayName[Maximum_C-String_Size+1];

For example:

char arr[4+1] = {'a', 'b', 'c', 'd'}

but arr[4] = {'a', 'b', 'c', 'd'} is also work

why need to add 1? thanks!

黃翊唐
  • 75
  • 1
  • 7

2 Answers2

0

There is no need to do this, unless you are defining something that will be used as a null-terminated string.

// these two definitions are equivalent
char a[5] = { 'a', 'b', 'c', 'd' };
char b[5] = { 'a', 'b', 'c', 'd', '\0' };

If you only want an array with 4 char values in it, and you won't be using that with anything that expects to find a string terminator, then you don't need to add an extra element.

paddy
  • 60,864
  • 6
  • 61
  • 103
0

If you’re storing a C-style string in an array, then you need an extra element for the string terminator.

Unlike C++, C does not have a unique string data type. In C, a string is simply a sequence of character values including a zero-valued terminator. The string "foo" is represented as the sequence {'f','o','o',0}. That terminator is how the various string handling functions know where the string ends. The terminator is not a printable character and is not counted towards the length of the string (strlen("foo") returns 3, not 4), however you need to set aside space to store it. So, if you need to store a string that’s N characters long, then the array in which it is stored needs to be at least N+1 elements wide to account for the terminator.

However, if you’re storing a sequence that’s not meant to be treated as a string (you don’t intend to print it or manipulate it with the string library functions), then you don’t need to set aside the extra element.

John Bode
  • 119,563
  • 19
  • 122
  • 198