【发布时间】:2018-02-27 11:07:33
【问题描述】:
我正在尝试编写一个 shell 程序,并且我有一个 inputBuffer 数组来保存输入的命令。我还有一个 historyBuffer 数组,它将保存过去输入的 10 个命令。我有全局变量:char historyBuffer[10][MAX_LINE];(其中 MAX_LINE == 80),在 main 里面我有 char inputBuffer[MAX_LINE]; 这是整个 main 函数:
int main(void){
int flag; //equals 1 if a command is followed by '&'
char *args[MAX_LINE/2+1]; //command line (of 80) must have <40 arguments
int child, //process id of the child process
status; //result from execvp system call
char inputBuffer[MAX_LINE];//buffer to hold the command entered
strcpy(historyBuffer, inputBuffer);
signal(SIGINT, shellHandler); //called when ^C is pressed
while(1){ //program terminates normally inside setup
flag = 0;
printf(" COMMAND->\n");
setup(inputBuffer,args,&flag); //get next comman
child = fork(); //creates a duplicate process
switch(child){
case -1:
perror("Could not fork the process");
break; /* perror is a library routine that displays a system
error message, according to the value of the system
vaiable "errno" which will be set during a function
(like fork) that was unable to successfully
complete its task */
case 0: //here is the child process
status = execvp(args[0], args);
if(status !=0){
perror("Error in execvp");
exit(-2); //terminate this process with error code -2
}
break;
default:
if(flag==0) //handle parent, wait for child
while(child != wait((int *) 0));
}//end switch
}//end while
}//end main
错误在于strcpy(historyBuffer, inputBuffer);这一行
我收到错误消息:expected 'char * __restirct__' but argument is of type 'char(*)[80]'
我不确定这是否与 strcpy 函数中的参数有关,是否与我调用 strcpy 的位置有关,或者是否与我声明 inputBuffer 或 historyBuffer 的方式有关?或者如果这是一个完全不同的问题而我没有注意到?
【问题讨论】:
-
你想用这个语句 strcpy(historyBuffer, inputBuffer); 达到什么目的? historyBuffer 是一个二维数组。此外 inputBuffer 没有初始化。代码没有意义。
-
strcpy(historyBuffer, inputBuffer);-->strcpy(historyBuffer[n], inputBuffer);其中n是 0..9 范围内的数字 -
最好是
strcpy(historyBuffer, inputBuffer);-->strncpy(historyBuffer[n], inputBuffer, MAX_LINE);其中n是0..9范围内的数字