following is the structure and I want to create array of this structure in C开发者_Python百科 and initialize, but confuse with how to initialize char **input
and char **output
.
typedef struct _test_data_vector {
char *api;
char **input;
char **output;
}vector_test_data;
following is what I tried.
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"}
}
};
You're very close, just specify type through compound literals (starting from C99)
This what I've tested with no warnings:
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]);
Otput: TEST: 3
be a little more specific , usually when you have to initialize a pointer to a pointer you do it like this:
char * charPointer;//this is the char you want the input to point at;
*input = charPointer;
I had to use pointer to pointer on a project to but if ther is any way you can avoid this it would be easyer
api, input, and output will, by default, be initialized to NULL. You can initialize api directly, but input and output must be allocated, either at compile time by defining arrays, or at runtime, perhaps via malloc. You really should provide more information about what you are trying to do in order to get a more helpful answer.
char text[] = "Input text"; char *output; struct _test_data_vector { char *api; char **input; char **output; }; struct _test_data_vector A = { NULL, &text, &output };
If you want to allocate space for them, you can also do:
struct _test_data_vector B = { "api", malloc( 5 * sizeof *B.input ), malloc( 10 * sizeof *B.output ) };
just make sure you check that the allocation was succesful. (I strongly advised against doing this, as it is much clearer to call malloc in non-initializer code.)
精彩评论