我正在编写一个程序,它需要一个命令行然后解析它,以便在输入中打印每个 argv 的字符串数组。
该代码给了我一个分段错误(核心转储)!
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
char **parse(int position ,char *argv[] ) ;
int main(int argc ,char *argv[])
{
int i=1;
int f=argc;
argc--;
while( i<f)
{
char commands[10];
char **argument=parse(argc,argv);
//parse(i ,argv ,commands ,argument) ;
printf("the argument[ %i ] is :%s \n",i,argument[i]);
argc-- ;
i++;
}
}
char **parse(int position ,char *argv[])
{
// char *commands;
char** arguments;
char *result ;
char buffer [30] ;
int count =0;
arguments = calloc(1, sizeof (char *));
strcpy(buffer,argv[position-1]); //copy the current argv to the buffer
result =strtok(buffer," ");
// strcpy(commands,result);
//result =strtok(buffer," ");
while(result !=NULL )
{
arguments[count] =result ;
++count;
arguments = realloc(arguments, sizeof (char *) * (count + 1));
result=strtok(NULL," ");
}
arguments[count] = NULL; //in order to call the execvp
return arguments;
}
谢谢你的帮助 。