Search code examples
cansi-c

How to initialize char** inside a struct


I have a struct

struct cmd{

  char **tokenized_cmd;
  int num_params;
}

at some point i need to initialize tokenized_cmd and pass values from another array into it

how to do that?


Solution

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

    or

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

    or the more flexible:

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