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!

3
  • 6
    You need to add 1 if you plan to treat arr as a NUL-terminated string. The extra element is to store, well, the NUL terminator. Commented Sep 22, 2020 at 3:15
  • End string of chars symbol '\n' Commented Sep 22, 2020 at 3:15
  • If you've found a tutorial or book that uses arr[4+1], stop using that tutorial or book and find a better one. Commented Sep 22, 2020 at 3:20

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.