如何初始化包含指针指针的结构

时间:2011-02-08 11:56:33

标签: c

以下是结构,我想在C中创建此结构的数组并进行初始化,但与如何初始化char **inputchar **output混淆。

typedef struct _test_data_vector {
    char *api;
    char **input;
    char **output;
}vector_test_data;

以下是我的尝试。

typedef struct _test_data_vector {
    char *api;
    char **input;
    char **output;
}vector_test_data;

vector_test_data data[] = {
    {
        "vector_push_back",
        {"1","2","3","4","5","6","7","8","9","10"},
        {"1","2","3","4","5","6","7","8","9","10"}
    }
};

4 个答案:

答案 0 :(得分:1)

你非常接近,只需通过compound literals指定类型(从C99开始)

这是我测试过的,没有任何警告:

typedef struct _test_data_vector {
    char *api;
    char **input;
    char **output;
}vector_test_data;

vector_test_data data[] = {
    {
        "vector_push_back",
        (char*[]){"1","2","3","4","5","6","7","8","9","10"},
        (char*[]){"1","2","3","4","5","6","7","8","9","10"}
    }
};

printf("TEST: %s", data[0].input[2]);

输出:测试:3

答案 1 :(得分:0)

稍微具体一点,通常当你必须初始化一个指向指针的指针时,你会这样做:

char * charPointer;//this is the char you want the input to point at;
*input = charPointer;

我不得不在指向项目的指针上使用指针,但如果有任何方法可以避免这种情况,那就更容易了

答案 2 :(得分:0)

默认情况下,

api,input和output将初始化为NULL。您可以直接初始化api,但必须在编译时通过定义数组或在运行时(可能通过malloc)分配输入和输出。你真的应该提供更多关于你要做什么的信息,以便得到更有帮助的答案。

答案 3 :(得分:0)

char text[] = "Input text";
char *output;
struct _test_data_vector {
    char *api;
    char **input;
    char **output;
};

struct _test_data_vector A = { NULL, &text, &output };

如果你想为他们分配空间,你也可以这样做:

struct _test_data_vector B = {
  "api",
  malloc( 5 * sizeof *B.input ),
  malloc( 10 * sizeof *B.output )
};

确保检查分配是否成功。 (我强烈地说 建议不要这样做,因为在非初始化代码中调用malloc要清楚得多。)