裏面我有一個結構如何初始化字符**一個struct
struct cmd{
char **tokenized_cmd;
int num_params;
}
在某些時候我需要初始化tokenized_cmd從另一個數組傳遞值到它
如何做到這一點?
裏面我有一個結構如何初始化字符**一個struct
struct cmd{
char **tokenized_cmd;
int num_params;
}
在某些時候我需要初始化tokenized_cmd從另一個數組傳遞值到它
如何做到這一點?
#include <stdio.h>
char *arr[] = {"one", "two"};
struct cmd {
char **tokenized_cmd;
int num_params;
} x = {arr, 2};
int main(void)
{
int i;
for (i = 0; i < x.num_params; i++)
printf("%s\n", x.tokenized_cmd[i]);
return 0;
}
或
#include <stdio.h>
struct cmd {
char **tokenized_cmd;
int num_params;
};
int main(void)
{
char *arr[] = {"one", "two"};
struct cmd x = {arr, 2};
int i;
for (i = 0; i < x.num_params; i++)
printf("%s\n", x.tokenized_cmd[i]);
return 0;
}
或更靈活:
#include <stdio.h>
#include <stdlib.h>
struct cmd {
char **tokenized_cmd;
int num_params;
};
struct cmd *cmd_init(char **token, int params)
{
struct cmd *x = malloc(sizeof *x);
if (x == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
x->tokenized_cmd = token;
x->num_params = params;
return x;
}
int main(void)
{
char *arr[] = {"one", "two"};
struct cmd *x = cmd_init(arr, 2);
int i;
for (i = 0; i < x->num_params; i++)
printf("%s\n", x->tokenized_cmd[i]);
free(x);
return 0;
}
這些選項不通過編譯 –
@LenaBru,你確定?使用'-pedantic -Wall -W -Wextra'爲我編譯沒有警告 –
[ideone](https://ideone.com/3Fg8cO) –
這取決於你想要初始化它是什麼。 –
字符串數組 –
可能的重複http://stackoverflow.com/questions/1088622/how-do-i-create-an-array-of-strings-in-c – sashoalm