Reputation: 159
I recently encounter a C interview coding question. A general function like "void Foo(char** sarr)". And it gives me a input
char* data[] = {"4352", "3242", "2432143", "234", "", "324", 0}
I am kind of new to C, but familiar with C++. For this case, I really don't know what does this '0' mean in this char* array. I know C has a terminator for string as '\0'. But what 0 means? Or this input is simply wrong/invalid? Thanks in advance.
Upvotes: 1
Views: 126
Reputation: 477
You declared an array of pointers, and the last element of the array is set to zero, which is effectively a NULL
pointer. In fact, the NULL
macro is usually defined as (void *) 0
, although its value is implementation dependent.
Upvotes: 2
Reputation: 655
NULL is a pointer defined usually as (void*) 0. This is used to declare the pointer which is pointing to nothing, it's usually used to show the end of list/tree, or that pointer was not allocated etc.
Upvotes: -1
Reputation: 781623
0
is one of the ways to write a null pointer constant in C. It would probably be more obvious if they'd written:
char* data[] = {"4352", "3242", "2432143", "234", "", "324", NULL};
which is equivalent.
The null pointer is being used as an indicator of the end of the array (similar to the way the character '\0'
marks the end of strings. If you're iterating over the array, you can use something like:
for (var i = 0; data[i] != 0; i++) {
// do something with data[i]
}
You can also use data[i] != NULL;
, they're equivalent.
Upvotes: 6
Reputation: 10557
In C/C++ NULL is effectively the same thing to numerical 0. It is ok to have NULL pointer as an element of an array of pointers. Your char *data[]
is an array of pointers.
This causes problems because in many cases it would be nice to distinguish integer 0 from NULL pointer. That is why since C++ 11 nullptr
and nullptr_t
were introduced. I would definitely recommend using them instead of NULL or 0.
Upvotes: 2