使用malloc初始化一个char指针数组

air*_*tis 1 c arrays malloc initialization

typedef struct {
    char * array[10];
} List;

int main(void) {
    List input;
    input.array = (char **)malloc(10 * sizeof(char));
    if (input.array == NULL)
        exit(EXIT_FAILURE);

    for (i = 0; i < 10; i++) {
        input.array[i] = (char *)malloc(10 * sizeof(char));
        if (input.array[i] == NULL)
            exit(EXIT_FAILURE);
    }
}
Run Code Online (Sandbox Code Playgroud)

我试图初始化一个10个char指针的数组,每个指针指向一个长度为10的不同字符串.

我从gcc收到以下错误:

incompatible types when assigning to type ‘char *[10]’ from type ‘char **’
Run Code Online (Sandbox Code Playgroud)

我对malloc的调用一定不正确,但是怎么回事?

zwo*_*wol 8

char *array[10]声明一个包含10个指针的数组char.没有必要malloc存储此阵列; 它嵌入在struct List.因此,第一次呼叫malloc是不必要的,就像之后的检查一样.

malloc对循环内部的调用以及之后的检查是正确的.

另外,在C中,不要转换返回值malloc; 它实际上可以隐藏错误.

另外,根据定义sizeof(char)是1 ,因此你永远不应该写它.

struct List
{
    char *array[10];
};

int
main(void)
{
    struct List input;
    for (int i = 0; i < 10; i++)
    {
        input.array[i] = malloc(10);
        if (!input.array[i])
            return EXIT_FAILURE;
    }
    /* presumably more code here */
    return 0;
}
Run Code Online (Sandbox Code Playgroud)