tags:

views:

71

answers:

5

How do I mark the end of a char* vector with '\0' to null-terminate it? If i have char* vector:

 char* param[5];

I thought of either

 param[4] = '\0';

or

char c = '\0';
param[4] = &c;

but none of them seem to work?

param is a char-pointer vector, supposed to point to 5 strings(char-vectors).

+3  A: 

Ok you are trying to end a vector of strings, something similar to what is passed to main as argv. In that case you just need to assign a null pointer:

param[4] = 0;
UncleZeiv
yes, like argv. so '\0' won't work in this case, because it describes value, not adress???
Rotor
@UncleZeiv: what is surprising is that `param[4] = '\0'`; should also work (even if the intent is mixed up) but the OP said it didn't.
kriss
@Rotor, on the machine level, `'\0'` is equivalent to `0`. However, for (at least some) compilers, the former is a `char` value, not a legal pointer value. Of course, you could cast it to pointer as `(char*)'\0'` - this would technically work, but is ugly and much more complicated than a plain `0`.
Péter Török
@Péter: `'\0'` is a character constant which in C has type `int`, not `char`.
schot
"(at least some) compilers" in this case means "C++ compilers", whereas the question is about C.
Steve Jessop
A: 

A char* vector is a vector of pointer to chars. You probably want a vector of char. In that case, you could write:

char vect[5] = { '\0' };

In this way the vector is initialized with all '\0' characters.

If you really want an array of char pointer you can do similarly:

char* vect[5] = { NULL };

All pointers to string will be initialized with NULL.

Luca Martini
+1  A: 

If you really have an array of char*, you can do:

 param[4] = "";

(Your second approach actually should work as long as you don't need param[4] to be valid when c goes out of scope.)

A better sentinel value usually would be the null pointer, however:

 param[4] = NULL;
jamesdlin
A: 

I would probably write something like below:

#include <stdio.h>

int main(){

    char* param[5] = {"1", "2", "3", "4", NULL};

    int i = 0;
    for (i = 0; param[i] ; i++){
       printf("%s\n", param[i]);
    }

}

Instead of NULL I could use 0, or '\0' as all are the same in the end (numerical value 0), but I believe using the NULL macro capture best the intention.

You can also write param[4] = NULL; if it's done after the initialization, and you param[4] = '\0'; should have worked (but looks more like obfuscation as you don't want a char at all, but a NULL pointer)

kriss
A: 

Your

char* param[5];

vector cannot be 'null terminated' - it is a vector of char pointers. You can only null terminate arrays of chars (by putting a '\0' whereever you want to terminate the char array.

Hence, I guess the correct answer to your question would be mu: Your question cannot be answered because it's based on incorrect assumptions. :-)

Frerich Raabe