I am having a problem where I do not understand the syntax on how to pass my array to a function and then access each argument. As it is now, while my array is in main, I can print each argument like:
Code:
printf("%s\n", args[0]);
printf("%s\n", args[1]);
etc...
However when I try to access it like above when I try to pass the args array to a function, I get a segmentation fault, I can only print the first element using:
Code:
printf("%s\n", args)
Could somebody please tell me if I'm passing the array incorrectly to the translate function and then subsequent functions, or how to acces each element beyond the first one.
Code:
void translate(char *input);
void list();
void changedir(char *list);
void lsdir(char *list);
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
main()
{
char *cptr, *csh;
char buffer[256];
char **args = NULL;
int nargs = 0;
printf("sh%% ");
cptr = fgets(buffer, 256, stdin);
csh = strtok(buffer, " ,\n");
while(strcmp(csh, "bye") != 0)
{
while(csh != NULL)
{
args = realloc(args, sizeof(char *)*(nargs + 1));
args[nargs] = malloc(strlen(csh) + 1);
strcpy(args[nargs], csh);
nargs++;
csh = strtok(NULL, " ,\n");
}
translate(*args);
nargs = 0;
printf("sh%% ");
cptr = fgets(buffer, 256, stdin);
csh = strtok(buffer, " ,\n");
}
}
void translate(char *input)
{/*This function translates what command is entered and calls
*appropriate function to execute command
*/
if(strcmp(input, "?") == 0)
{
list();
}
else if(strcmp(input, "cd") == 0)
{
changedir(input);
}
else if(strcmp(input, "ls") == 0)
{
lsdir(input);
}
else return;
}
void list()
{/*This function prints a list of all available commands when
*? is entered
*/
printf("\n***List of Available Commands***\n");
printf("? - Displays this message\n");
printf("bye - Exits UNIX shell\n");
printf("cd - changes current directory\n");
printf("ls - lists files in current directory\n");
printf("\n");
}
void changedir(char *input)
{
}
void lsdir(char *input)
{
int pid;
int status = 0;
pid = fork();
if(pid == -1)
printf("error!!!\n");
else if(pid == 0)
{
execvp(list, list);
exit(1);
}
else if(pid > 0)
{
waitpid(pid, &status, 0);
}
printf("%d\n", pid);
}