I am working on a few functions that will work together to initialize a list of char *
's as a command list. I am storing them in a char **
, which I want to alter whenever it's necessary to insert another command. When I run the insert command with a single char *command, It says that commandList[0] = "ls"
inside of the insert function, but in the initializeCommands
function it says that testCommands[0] = NULL
. Can anyone explain why this is happening?
void insertCommand(char *command, char **commandList){
if(commandList[0] == NULL){ // no commands
commandList = (char **)malloc(sizeof(char *) * 2);
commandList[0] = (char *)malloc(strlen(command) * sizeof(char));
commandList[0] = command;
printf("Commandlist[0]: %s\n", commandList[0]);
commandList[1] = NULL;
} else { // one or more commands
int i = 0;
while(commandList[i] != NULL){
i++;
}
commandList = (char **)realloc(sizeof(char *) * (i + 1));
commandList[i - 1] = (char *)malloc(sizeof(char) * strlen(command));
commandList[i] = NULL;
}
return;
}
The printf statement above shows that commandList[0] != NULL
char **initializeCommands(){
char **testCommands = createCommandList();
insertCommand("ls", testCommands);
printf("testCommand[0]: %s\n", testCommands[0]);
return testCommands;
}
The printf statement above shows that testCommands[0] == NULL
create command list
char **createCommandList(){
char **commandList = (char **)malloc(sizeof(char *));
commandList[0] = NULL;
return commandList;
}