如何在结构中初始化char**

mspsb9vt  于 2023-03-28  发布在  其他
关注(0)|答案(1)|浏览(150)

我有一个结构

struct cmd{

  char **tokenized_cmd;
  int num_params;
}

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

oaxa6hgo

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

相关问题