3

If I declare a string with 10 elements like this:

char s[10];

then does the '\0'at the end occupy the 10th place or the 11th? Basically my question is that do we get 1 element less in the string?

And if I use the strlen() function to find this string's length, will the return value be inclusive of the null? I.e if the string is "boy", will the function give me 3 or 4?

Mat
  • 202,337
  • 40
  • 393
  • 406
Nirvan
  • 147
  • 1
  • 1
  • 6
  • the \0 can be inserted anywhere from index 0 to index 9 inclusive. It cannot appear in index 10 (The index range here is 0- 9). – Lunar Mushrooms Apr 15 '12 at 12:28
  • As you are using C++ I will point out that you should be using the string class rather then arrays of `char` (or `char*` for that matter [fyi, not exactly the same]) Though I believe you are looking at embedded stuff, and that's like some alternate reality where nothing makes sense. – thecoshman Apr 17 '12 at 08:30

4 Answers4

10

There is no 11th place, ie, yes, that is one less element to use.

Don't put a string longer than 9 chars in there. Strlen() does not include the null terminator.

Eg:

char s[]="hello"; 

s is an array of 6 chars, but the strlen() of s is 5.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
CodeClown42
  • 11,194
  • 1
  • 32
  • 67
  • As this is tagged C++, I think that's a safe assumption :-) – Philip Kendall Apr 15 '12 at 12:28
  • I knew those had some kind of purpose ;) – CodeClown42 Apr 15 '12 at 12:32
  • An example of a language that does it differently is Modula2. There the terminating null is omitted if the number of characters is equal to the array count. All functions behave like C "-n" variants, one has to pass the upper bound of the buffer for every action, to allow the runtime to handle this case. – Marco van de Voort Apr 15 '12 at 12:40
  • Upvoting this for fairness, because the OP doesn't seem to accept any answer anyway. – ereOn Apr 16 '12 at 14:46
2

Yes, the \0 character will occupy the 10th place. Meaning, the string will only contains 9 input characters. And no, strlen() does not count the null character.

Kemal Fadillah
  • 9,760
  • 3
  • 45
  • 63
2

If you declare an array like that, it doesn't need to have a zero byte at the end. If you call any functions that expect a string on it, it almost certainly will result in a crash. You need to initialize the array:

char s[] = "This is a test."

If you do something like this:

char s[10] = "012345678"
printf("%d\n", strlen(s));

It will obviously print 9. You can't put 10 characters in that array, since the null byte would get written out of the array bounds.

Staven
  • 3,113
  • 16
  • 20
1

If you declare an array of 10 characters, you must keep in mind that one of them has to be used for the string terminator, so you can store a maximum of 9 characters.

strlen, instead, returns only the number of "logical" characters, i.e. it won't count the null terminator.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299