我有一个结构
struct cmd{ char **tokenized_cmd; int num_params; }
在某些时候我需要初始化tokenized_cmd并将另一个数组的值传递给它怎么做呢?
oaxa6hgo1#
#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; }
1条答案
按热度按时间oaxa6hgo1#
或
或者更灵活: