c - Passing an array of pointers by reference -
i'm trying commands keyboard in similiar fashion command line args int main( int argc, char *argv[] )
but in separate function. when parse , print them within scope of getcmd()
function looks , behaves intended, return main function become bunch of garbage. questions below 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)); (size_t = 0; < (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 relevant i'm using vs 2015 community visual c++ compiler on 64 bit processor, windows 7 os.
my questions:
- how should pass cmd , args[] reference?
- are there accepted idioms deal sort of situations?
i've looked trough few of similiar questions , couldn't find solution works in context, if question duplicate, tell me , i'll close it.since i'm new stackoverflow question formatting tips appreciated. cheers! (:
strtok_s()
return pointer buffer it's parsing (input
here).
input
lives on getcmd()
stack. dies moment getcmd()
returns. on addresses pointing input
, had been stored in args
's elements not point valid memory more.
the code needs allocate fresh memory , copy strtok_s()
returned pointer to.
have on ow can done:
#include <stdio.h> #include <stdlib.h> #include <string.h> void getcmd(char **pcmd, char *args[], size_t s) { char input[81] = { 0 }; char *next_token = null; printf("$ "); fgets(input, 81, stdin); input[strcspn(input, "\n")] = 0; (*pcmd) = _strdup(strtok_s(input, " ", &next_token)); if (!strcmp(*pcmd, "mv")) { args[0] = _strdup(strtok_s(null, " ", &next_token)); args[1] = _strdup(strtok_s(null, " ", &next_token)); printf("\n\n%s\n%s\n%s\n\n", *pcmd, args[0], args[1]); } } #define args_max (5) int main(void) { char *cmd, *args[args_max] = {0}; getcmd(&cmd, args, args_max); printf("\n\n%s \n%s\n%s", cmd, args[0], args[1]); /* clean up. */ free(cmd); (size_t = 0; < args_max; ++i) { free(args[i]); } return 0; }
Comments
Post a Comment