初始化字符串数组

初始化char**的正确方法是什么? 我在尝试时遇到覆盖错误 – 未初始化指针读取(UNINIT):

 char **values = NULL; 

要么

 char **values = { NULL }; 

此示例程序说明了C字符串数组的初始化。

 #include  const char * array[] = { "First entry", "Second entry", "Third entry", }; #define n_array (sizeof (array) / sizeof (const char *)) int main () { int i; for (i = 0; i < n_array; i++) { printf ("%d: %s\n", i, array[i]); } return 0; } 

它打印出以下内容:

 0: First entry 1: Second entry 2: Third entry 

它很好,只做char **strings;char **strings = NULL ,或char **strings = {NULL}

但要初始化它你必须使用malloc:

 #include  #include  #include  int main(){ // allocate space for 5 pointers to strings char **strings = (char**)malloc(5*sizeof(char*)); int i = 0; //allocate space for each string // here allocate 50 bytes, which is more than enough for the strings for(i = 0; i < 5; i++){ printf("%d\n", i); strings[i] = (char*)malloc(50*sizeof(char)); } //assign them all something sprintf(strings[0], "bird goes tweet"); sprintf(strings[1], "mouse goes squeak"); sprintf(strings[2], "cow goes moo"); sprintf(strings[3], "frog goes croak"); sprintf(strings[4], "what does the fox say?"); // Print it out for(i = 0; i < 5; i++){ printf("Line #%d(length: %lu): %s\n", i, strlen(strings[i]),strings[i]); } //Free each string for(i = 0; i < 5; i++){ free(strings[i]); } //finally release the first string free(strings); return 0; } 

没有正确的方法,但您可以初始化一系列文字:

 char **values = (char *[]){"a", "b", "c"}; 

或者您可以分配每个并初始化它:

 char **values = malloc(sizeof(char*) * s); for(...) { values[i] = malloc(sizeof(char) * l); //or values[i] = "hello"; }