c - 如何在结构体中初始化 char**

标签 c ansi-c

我有一个结构

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

关于c - 如何在结构体中初始化 char**,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23579526/

相关文章:

c - 字符串数组初始化

c - 如何声明指向 volatile 结构的指针

c++ - Matlab 代码生成 : Does not support anonymous functions

c - 为什么这个C字符串化宏在扩展时会损坏?

c - 我计算字符串中元音数量的程序总是输出 0 或 1

c - 字符串数组转换

java - 是否存在 if 语句无法被跳转表替代的情况?

在 ANSI C 的控制流语句中组合比较测试

c - pow(1,0) 返回 0?

c++ - 如何在 CLI 中打印表格