0
  • 我为我的 linux mini-shell 分配编写了以下代码,并且不断收到以下错误消息。- 警告:从不兼容的指针类型传递 'strcat' 的参数 2 - /usr/include/string.h:136:14:注意:预期的 'const char * restrict ' 但参数的类型是 'char **'</p >

  • cld 任何人都通过它并告诉我出了什么问题?

编码:

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&gt;");

        //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;
}
4

1 回答 1

1

strcat的第二个参数是类型const char*,但您试图传递一个 char 指针数组。

如果要将所有arguments数组添加到字符串中,则应遍历数组,strcat每次调用单个数组项。

for (i=0; i<num_of_args; i++) {
    strcat(prog, arguments[i]);
}

如果要添加单个参数,请确定其数组索引并使用

strcat(prog, arguments[index]);
于 2012-11-01T07:59:44.403 回答