我为我的 linux mini-shell 分配编写了以下代码,并且我 不断收到以下错误消息。 - 警告:从不兼容的指针类型传递“strcat”的参数 2 -/usr/include/string.h:136:14:注意:预期为“const char * restrict”,但是 参数的类型为“char **”
请谁检查一下并告诉我出了什么问题?
代码:
int countArgs(char n_args[], ...){
va_list ap;
int i, t;
va_start(ap, n_args);
for(i=0;t = va_arg(ap, int);i++){ return t; }
va_end(ap);
}
char *parse(char buffer[],int num_of_args, char *arguments[])
{
arguments[num_of_args+1]=NULL;
int i;
for(i=0;i<num_of_args+1;i++){
do
{
arguments[i]= strtok(buffer, " ");
}
while(arguments!=NULL);
}
return arguments;
}
int main(int argc, char **argv)
char buffer[512];
char *path = "/bin/";
while(1)
{
//print the prompt
printf("myShell>");
//get input
fgets(buffer, 512, stdin);
//fork!
int pid = fork(); //Error checking to see if fork works
//If pid !=0 then it's the parent
if(pid!=0)
{
wait(NULL);
}
else
{
//if pid = 0 then we're at teh child
//Count the number of arguments
int num_of_args = countArgs(buffer);
//create an array of pointers for the arguments to be
//passed to execcv.
char *arguments[num_of_args+1];
//parse the input and arguments will have all the arguments
// to be passed to the program
parse(buffer, num_of_args, arguments);
arguments[num_of_args+1] = NULL;
//This will be the final path to the program that we will pass to execv
char prog[512];
//First we copy a /bin/ to prog
strcpy(prog, path);
//Then we concancate the program name to /bin/
//If the program name is ls, then it'll be /bin/ls
strcat(prog, arguments);
//pass the prepared arguments to execv and we're done!
int rv = execv(prog, arguments);
}
}
return 0;
}
最佳答案
strcat 的第二个参数属于 const char*
类型,但您试图传递 char 指针数组。
如果要将所有arguments
数组添加到字符串中,则应循环遍历该数组,每次使用单个数组项调用strcat
。
for (i=0; i<num_of_args; i++) {
strcat(prog, arguments[i]);
}
如果您想添加单个参数,请确定其数组索引并使用
strcat(prog, arguments[index]);
关于c - 如何在c中编写迷你shell时解析输入命令行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13172688/