初始化字符串数组

Lio*_*mov 28 c initialization

什么是正确的初始化方法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)

  • @teMkaa 使用 `#define` 只是一个风格问题;就我个人而言,我不会这样做。在“main”函数中,您可以轻松定义另一个 int 变量并将其分配给“sizeof (array) / sizeof (const char *)”。 (2认同)

Nic*_*ert 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;
}
Run Code Online (Sandbox Code Playgroud)

  • (我会考虑一些c-grammar nazzi在malloc之前评论类型转换) (2认同)

Vla*_*adp 7

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

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)