什么是正确的初始化方法char**?我在尝试时遇到覆盖错误 - 未初始化指针读取(UNINIT):
char **values = NULL;
Run Code Online (Sandbox Code Playgroud)
要么
char **values = { NULL };
Run Code Online (Sandbox Code Playgroud)
Ebr*_*imi 47
此示例程序说明了C字符串数组的初始化.
#include <stdio.h>
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;
}
Run Code Online (Sandbox Code Playgroud)
它打印出以下内容:
0: First entry
1: Second entry
2: Third entry
Run Code Online (Sandbox Code Playgroud)
其优良的只是做char **strings;,char **strings = NULL或char **strings = {NULL}
但要初始化它你必须使用malloc:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
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;
}
Run Code Online (Sandbox Code Playgroud)
没有正确的方法,但您可以初始化一系列文字:
char **values = (char *[]){"a", "b", "c"};
Run Code Online (Sandbox Code Playgroud)
或者您可以分配每个并初始化它:
char **values = malloc(sizeof(char*) * s);
for(...)
{
values[i] = malloc(sizeof(char) * l);
//or
values[i] = "hello";
}
Run Code Online (Sandbox Code Playgroud)