【问题标题】:C strcat - warning: passing arg 2 of `strcat' makes pointer from integer without a castC strcat - 警告:传递 `strcat' 的 arg 2 使指针从整数而不进行强制转换
【发布时间】:2013-10-10 22:56:05
【问题描述】:

下面的程序有问题。我正在尝试扫描用户输入的字符串命令以查找某些单词。我现在的主要问题是,当我运行以下命令时,我收到一条警告说“传递 `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);
}

【问题讨论】:

    标签: c strcat


    【解决方案1】:

    你的程序有很多问题;例如,您永远不会初始化 firstthree

    您看到特定错误的原因是因为这个调用:

    strcat(firstthree, s[i]);
    

    schar *,所以 s[i]char,但 strcat 期望这两个参数都是指向以空值结尾的字符串的指针。看起来你想要的是这样的:

    char firstthree[4] = { 0 };
    for (int i = 0; i < 3; i++)
    {
        firstthree[i] = s[i];
        printf("Hello %s\n", firstthree);
    }
    

    【讨论】:

      【解决方案2】:

      您不能使用 strcat() 来执行此操作;它需要两个 char* 作为参数,而不是一个 char* 和一个 char。如果您的平台上可用,您可以使用 strncat()。

      【讨论】:

      • strncat 的签名是 char *strncat(char *dest, const char *src, size_t n); 它还需要两个 char*s 作为参数,所以它不能解决问题。
      • 当然可以——你在开玩笑吧?他可以使用它来复制从 s 到 firstthree 的三个字符,而不是使用显式循环复制它们。
      • 好的。考虑到这是新用户提出的第一个问题,所以给出一个不太简洁的答案会有所帮助:-)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-30
      • 2013-09-15
      • 2019-09-17
      • 1970-01-01
      • 1970-01-01
      • 2012-11-03
      • 1970-01-01
      相关资源
      最近更新 更多