Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- void populateArray(char* line, char** cmd){
- printf("INPUT LINE: %s\n", line);
- char *token = strtok (line, " ");
- int n_spaces = 0, i;
- /* split string and append tokens to 'cmd' */
- while (token) {
- cmd = realloc (cmd, sizeof (char*) * ++n_spaces);
- if (cmd == NULL)
- exit (-1); //memory allocation failed
- cmd[n_spaces-1] = token;
- token = strtok (NULL, " ");
- }
- /* realloc one extra element for the last NULL */
- cmd = realloc (cmd, sizeof (char*) * (n_spaces+1));
- cmd[n_spaces] = 0;
- /* print the cmd */
- for (i = 0; i < (n_spaces+1); ++i)
- printf ("cmd[%d] = %s\n", i, cmd[i]);
- /* free the memory allocated */
- //free (cmd);
- }
- int main (int argc, char* argv[])
- {
- //char *cmd1[64];
- // char *cmd2[64];
- // char *line = "ls -l -a"; // this won't work
- // char * line = strdup("ls -l -a"); // this WORKS
- char line[] = "ls -l -a"; // this WORKS, too
- char **cmd3 = (char**)malloc(sizeof(char*));
- cmd3[0] = (char*)malloc(sizeof(char) * 64);
- //populateArray(line, cmd1);
- populateArray(line, cmd3);
- return 1;
- }
Advertisement
Add Comment
Please, Sign In to add comment