C语言 初始化字符串数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21023605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Initialize array of strings
提问by Lior Avramov
What is the right way to initialize char**?
I get coverity error - Uninitialized pointer read (UNINIT) when trying:
什么是初始化的正确方法char**?尝试时出现覆盖错误 - 未初始化的指针读取(UNINIT):
char **values = NULL;
or
或者
char **values = { NULL };
回答by Ebrahimi
This example program illustrates initialization of an array of C strings.
此示例程序说明了 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;
}
It prints out the following:
它打印出以下内容:
0: First entry
1: Second entry
2: Third entry
回答by Nick Beeuwsaert
Its fine to just do char **strings;, char **strings = NULL, or char **strings = {NULL}
只做char **strings;, char **strings = NULL, 或char **strings = {NULL}
but to initialize it you'd have to use malloc:
但是要初始化它,您必须使用 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;
}
回答by Vladp
There is no right way, but you can initialize an array of literals:
没有正确的方法,但您可以初始化一个文字数组:
char **values = (char *[]){"a", "b", "c"};
or you can allocate each and initialize it:
或者您可以分配每个并初始化它:
char **values = malloc(sizeof(char*) * s);
for(...)
{
values[i] = malloc(sizeof(char) * l);
//or
values[i] = "hello";
}

