gpt4 book ai didi

c- 从不兼容的指针类型传递参数 1 of 'strcpy'

转载 作者:行者123 更新时间:2023-11-30 16:41:21 25 4
gpt4 key购买 nike

我正在尝试编写一个 shell 程序,并且我有一个 inputBuffer 数组来保存输入的命令。我还有一个 HistoryBuffer 数组,用于保存过去输入的 10 个命令。我有全局变量: char HistoryBuffer[10][MAX_LINE]; (其中 MAX_LINE == 80),在 main 内部我有 char inputBuffer[MAX_LINE]; 这里是整个主要功能:

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);

我收到错误消息:预期为“char * __restirct__”,但参数的类型为“char(*)[80]”

我不确定这是否是 strcpy 函数中参数的问题,是否是我调用 strcpy 的位置的问题,或者是否是我声明 inputBuffer 或 HistoryBuffer 的方式的问题?或者如果这是一个我没有注意到的完全不同的问题?

最佳答案

strcpy 的两个参数应该是指向char(即“字符串”)的指针。但是 historyBuffer 是一个指向 char 的指针数组(即指向字符串的指针)。

当您将 historyBuffer 作为参数传递时,您需要取消引用它,例如历史缓冲区[0]。此外,由于您的数组是固定的、已知的大小,因此您确实应该使用 strncpy ,它不太容易溢出。

这将修复错误,但您的代码仍然没有任何意义。 strcpy 只是执行一次内存复制,当 inputBuffer 尚未使用任何内容初始化时,您会在代码开头调用它。所以这是没有意义的。

如果您确实想将每个inputBuffer存储在historyBuffer中,则需要在每次读取后调用strcpy,并有设置一些索引来指示 historyBuffer 的哪些元素包含有效数据以及接下来应该覆盖哪个历史记录条目。

关于c- 从不兼容的指针类型传递参数 1 of 'strcpy',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46287303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com