如何在struct中初始化char **

时间:2014-05-10 09:45:41

标签: c ansi

我有一个结构

struct cmd{

  char **tokenized_cmd;
  int num_params;
}

在某些时候我需要初始化tokenized_cmd并将另一个数组中的值传递给它

怎么做?

1 个答案:

答案 0 :(得分:1)

#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;
}