我下面的程序有问题。我正在尝试浏览用户输入的某些单词的字符串命令。我现在的主要问题是,当我运行以下命令时,我得到一个警告,即“传递'strcat'的arg 2会使指针从整数转换而无需强制转换”。我的意图是遍历字符串“ s”的前三个字符,将它们连接到字符串“ firstthree”,然后检查字符串“ firstthree”的值。任何帮助表示赞赏。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <readline/readline.h>
#include <readline/history.h>
/* Simple example of using gnu readline to get lines of input from a user.
Needs to be linked with -lreadline -lcurses
add_history tells the readline library to add the line to it's
internal histiry, so that using up-arrow (or ^p) will allows the user
to see/edit previous lines.
*/
int main(int argc, char **argv) {
char *s;
while (s=readline("Enter Name: ")) {
add_history(s); /* adds the line to the readline history buffer */
printf("Hello %s\n",s);/*output message to the user*/
char *firstthree;
int i;
for(i = 0; i < 3; i++){
strcat(firstthree, s[i]);
printf("Hello %s\n",firstthree);//checking to see the character added to the end of the string
}
printf("Hey %s\n",firstthree);/*prints out the first three characters*/
free(s); /* clean up! */
free(firstthree);
}
return(0);
}
Run Code Online (Sandbox Code Playgroud)
您的程序有很多问题;firstthree例如,您永远不会初始化。
您收到所看到的特定错误的原因是由于此调用:
strcat(firstthree, s[i]);
Run Code Online (Sandbox Code Playgroud)
s是一个char *,s[i]一个也是char,但是strcat希望两个参数都是指向以null终止的字符串的指针。您似乎想要的是这样的:
char firstthree[4] = { 0 };
for (int i = 0; i < 3; i++)
{
firstthree[i] = s[i];
printf("Hello %s\n", firstthree);
}
Run Code Online (Sandbox Code Playgroud)