How is NULL (or 0 or '\0') behaved in unsigned char array and char array? In a char array NULL determines the end of the char array. Is it the same case with an unsigned char array? If not how can we determine the end of an unsigned char array?
-
The end of either is `'\0'`, which is the NUL character. It has nothing to do with `NULL`. – chris Oct 24 '13 at 01:51
-
is NUL or '\0' different from NULL in c++ – annunarcist Oct 24 '13 at 01:52
-
`'\0'` has the same value as a signed or unsigned char. The byte is all zeros... – nhgrif Oct 24 '13 at 01:53
-
2In essence they all mean 0. – Retired Ninja Oct 24 '13 at 01:53
-
Unless you're burying a nulchar in the middle of a string, there is little reason to use ``\0`` to begin with. Just use 0. – WhozCraig Oct 24 '13 at 02:09
2 Answers
The exact definition of NULL
is implementation-defined; all that's guaranteed about it is that it's a macro that expands to a null pointer constant. In turn, a null pointer constant is "an integral constant expression (5.19) prvalue of integer type that evaluates to zero or a prvalue of type std::nullptr_t
." It may or may not be convertible to char
or unsigned char
; it should only really be used with pointers.
0
is a literal of type int
having a value of zero. '\0'
is a literal of type char having a value of zero. Either is implicitly convertible to unsigned char
, producing a value of zero.
It is purely a convention that a string in C and C++ is often represented as a sequence of char
s that ends at the first zero value. Nothing prevents you from declaring a char array that doesn't follow this convention:
char embedded_zero[] = {'a', '\0', 'b'};
Of course, a function that expects its argument to follow the convention would stop at the first zero: strlen(embedded_zero) == 1;
.
You can, of course, write a function that takes unsigned char*
and follows a similar convention, requiring the caller to indicate the end of the sequence with an element having zero value. Or, you may write a function that takes a second parameter indicating the length of the sequence. You decide which approach better fits your design.

- 50,461
- 4
- 56
- 85
Strictly speaking, '\0'
denotes the end of a string literal, not the end of just any char
array. For example, if you declare an array without initializing it to a string literal, there would be no end marker in it.
If you initialize an array of unsigned char
s with a string literal, though, you would get the same '\0'
end marker as in a regular character array. In other words, in the code below
char s[] = "abc";
unsigned char u[] = "abc";
s[3]
and u[3]
contain identical values of '\0'
.

- 714,442
- 84
- 1,110
- 1,523