-4

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?

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
Lena Bru
  • 13,521
  • 11
  • 61
  • 126

1 Answers1

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

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;
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94