Ending char* vector in c
How do I mark the end of a开发者_如何学Python 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).
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;
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;
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
.
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)
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. :-)
精彩评论