初始化字符串数组

时间:2014-01-09 14:56:19

标签: c initialization

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

char **values = NULL;

char **values = { NULL };

3 个答案:

答案 0 :(得分:46)

此示例程序说明了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;
}

打印出以下内容:

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

答案 1 :(得分:8)

可以char **strings;char **strings = NULLchar **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;
}

答案 2 :(得分:7)

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

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

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

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