Guest User

Untitled

a guest
Oct 25th, 2014
353
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5.  
  6. void populateArray(char* line, char** cmd){
  7. printf("INPUT LINE: %s\n", line);
  8. char *token = strtok (line, " ");
  9. int n_spaces = 0, i;
  10.  
  11. /* split string and append tokens to 'cmd' */
  12. while (token) {
  13. cmd = realloc (cmd, sizeof (char*) * ++n_spaces);
  14.  
  15. if (cmd == NULL)
  16. exit (-1); //memory allocation failed
  17.  
  18. cmd[n_spaces-1] = token;
  19.  
  20. token = strtok (NULL, " ");
  21. }
  22.  
  23. /* realloc one extra element for the last NULL */
  24.  
  25. cmd = realloc (cmd, sizeof (char*) * (n_spaces+1));
  26. cmd[n_spaces] = 0;
  27.  
  28. /* print the cmd */
  29.  
  30. for (i = 0; i < (n_spaces+1); ++i)
  31. printf ("cmd[%d] = %s\n", i, cmd[i]);
  32.  
  33. /* free the memory allocated */
  34.  
  35. //free (cmd);
  36. }
  37.  
  38. int main (int argc, char* argv[])
  39. {
  40. //char *cmd1[64];
  41. // char *cmd2[64];
  42.  
  43. // char *line = "ls -l -a"; // this won't work
  44. // char * line = strdup("ls -l -a"); // this WORKS
  45. char line[] = "ls -l -a"; // this WORKS, too
  46.  
  47. char **cmd3 = (char**)malloc(sizeof(char*));
  48. cmd3[0] = (char*)malloc(sizeof(char) * 64);
  49.  
  50. //populateArray(line, cmd1);
  51. populateArray(line, cmd3);
  52.  
  53. return 1;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment