-3
#include<iostream>
#include<string.h>

using namespace std;

int main() {
    char b[] = {'a','b',' ','c'};
    cout << sizeof(b) << endl;
    cout << strlen(b) << endl;
    return 0;
}

Why the above output is 4,6 isnt that 4,4 is the correct answer?

T.g
  • 169
  • 2
  • 11

4 Answers4

5

The behaviour of your code is undefined: strlen requires that b must contain a NUL character within the bounds of the array.

(Note that ' ' is a space, not NUL. A space is processed no differently by strlen to any other non-NUL character.)

If you had written

char b[5]={'a','b',' ','c'};

then C++ would have set the final element of b to 0 (i.e. NUL) for you.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

Your code exhibits undefined behavior:

The behavior of strlen is not defined if the argument passed to it is not NUL-terminated.

You seem to confuse the NUL character with the space character.

1

what does strlen do if it enounter a space in between char array?

While all the other answers (according to your code sample, legitimately!!!) hint to the undefined behaviour due to the missing null character within your array, I'll be answering your original question:

Nothing special, it will count the space just as any other character (especially, it won't stop processing the string as you seem to have assumed)...

Aconcagua
  • 24,880
  • 4
  • 34
  • 59
0

strlen traverses the array until it encounters a NULL character. Your array does not contain NULL characters (ASCII 0) but it contains a space (ASCII 32).

So strlen continues past your array. It happens to exist a NULL character at position 6 (two characters after the end of the array in memory), so string length is 6. Subsequent executions of this function could return different values, as memory content outside the array is undefined. It may also crash.

Mario Cianciolo
  • 1,223
  • 10
  • 17
  • why it happens to exist that null character ,two characters after end of array – T.g Mar 14 '18 at 11:43
  • @T.g Just by accident. Your array occupies a bunch of bytes in memory. As on the stack, it is quite likely that there are some other (uninitialised!!!) bytes accessible (again: pure accident! - you could have quite well run into an access violation instead), and one of these bytes (the 6th one) "happened" to contain a null value, but it could have contained any other value as well... – Aconcagua Mar 14 '18 at 11:55
  • @T.g data after the array is unitialized (read: random) – Mario Cianciolo Mar 14 '18 at 12:26