-1

I am suppose to store the pointer to a command into a 2d array. Below is a little bit of code that I am using, but I dont know how to get the desired result.

#define MAX_LINE_LENGTH 1024
#define MAX_COMMANDS 10
char *commandHistory[MAX_COMMANDS][MAX_LINE_LENGTH + 1];


char *token;
token = strtok(line, LSH_TOK_DELIM);
printf("%s\n", token); //prints out the command I want to store the pointer to
commandHistory[i++][0] = token; //what do I do here?
connor moore
  • 611
  • 1
  • 8
  • 18

2 Answers2

0

You need to allocate a copy of the string and store that. The simplest way to do that is like this:

commandHistory[i++][0] = strdup(token);

When your program is finished with these, you should free each one that is allocated using strdup.

Edward
  • 6,964
  • 2
  • 29
  • 55
  • Lets say commandHistory[0][0] = ls. I have another token thats a string that I need to add onto commandHistory[0][0]. How would I do this? – connor moore Apr 07 '15 at 01:18
  • That would be [a different question](http://stackoverflow.com/questions/10279718/append-char-to-string-in-c). – Edward Apr 07 '15 at 01:21
0

You also need not to set second dimension. Declare it like this.

char *commandHistory[MAX_COMMANDS]={};

This is an array of pointers. You can enforce the MAX_LINE_LENGTH of the string read from input source and as others mentioned store the newly allocated string in the location like:

commandHistory[i++]= strdup(token);

If you want to go with 2 dimensional array then you need to copy the token into the array like:

char commandHistory[MAX_COMMANDS][MAX_LINE_LENGTH + 1] ={};
strcpy_s(commandHistory[i++], MAX_LINE_LENGTH+1, token);
Ethaan
  • 11,291
  • 5
  • 35
  • 45
Sandeep
  • 1
  • 1