I'm trying to get commands from the keyboard in a similiar fashion as command line args int main( int argc, char *argv[] )
but in a separate function. When I parse and print them within the scope of the getCmd()
function all looks and behaves as intended, but as soon as they return to the main function they become a bunch of garbage. My questions are below the code.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
void getCmd(char *cmd, char *args[])
{
char input[81] = { 0 };
char *next_token = NULL;
printf("$ ");
fgets(input, 81, stdin);
input[strcspn(input, "\n")] = 0;
cmd = strtok_s(input, " ", &next_token);
if (!strcmp(cmd, "mv"))
{
args[0] = strtok_s(NULL, " ", &next_token);
args[1] = strtok_s(NULL, " ", &next_token);
printf("\n\n%s\n%s\n%s\n\n", cmd, args[0], args[1]);
}
}
int main(void)
{
char *cmd = NULL, *args[5];
cmd = (char *)calloc(20,sizeof(char));
for (size_t i = 0; i < (size_t)5; i++)
{
args[i] = (char *)calloc(20,sizeof(char));
}
getCmd(cmd, args);
printf("\n\n%s \n%s\n%s", cmd, args[0], args[1]);
return 0;
}
I don't think its relevant but I'm using VS 2015 Community with the Visual C++ compiler on a 64 bit processor, Windows 7 OS.
My questions:
- How should I pass the cmd and args[] by reference?
- Are there any widely accepted idioms that deal with this sort of situations?
I've looked trough a few of the similiar questions and couldn't find a solution that works in this context, if the question is a duplicate, tell me and I'll close it.Since I'm new to stackoverflow any question formatting tips would be greatly appreciated. Cheers! (: