array of characters: it doesn't print the exact size!

in this code, the output is 6 instead of 5, i didn't get it!
the condition is to not include '\0', is the compiler counting it ?

1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;
int main(){
char a[5]={'1','2','3','4','5'};
int c=0;
while(a[c]!='\0')
    c++;
cout<<c<<endl;
}
How do you expect the loop to find a '\0' when the array doesn't contain such a character.
How do you expect the loop to find a '\0' when the array doesn't contain such a character.

\0 is exist in the array, it's the termination character.

if i was wrong, can you explain please ?
Last edited on
\0 is exist in the array, it's the termination character.

No it doesn't exist in the array. There is no automatic termination character for character arrays.

...and to clarify further, you're thinking of string literals. They will put a null terminator on the end. But you have to give it enough room (the actual length of the string + 1).

1
2
char a[6] = "hello";
// a --> { 'h', 'e', 'l', 'l', 'o', '\0' } 


You're also trying to implement strlen, it seems.
http://www.cplusplus.com/reference/cstring/strlen/

Oh yeah, and... since you're using C++, you should use std::string objects instead.

http://www.cplusplus.com/reference/string/string/length/
1
2
3
4
5
6
7
8
9
10
// string::length
#include <iostream>
#include <string>

int main ()
{
  std::string str ("Test string");
  std::cout << "The size of str is " << str.length() << " bytes.\n";
  return 0;
}
Last edited on
Topic archived. No new replies allowed.