首页 > 解决方案 > c 中的连接字符:“char”类型的参数与“const char*”类型的参数不兼容

问题描述

我正在尝试编写一个在 C 中连接 2 个值而不使用strcat().

char cat (char s1, char s2){
    char s3[200];
    strcpy(s3,s1);
    strcpy(s3+strlen(s1),s2);
    return s3;
}

这是我的代码,但它给出了这个错误:

argument of type "char" is incompatible with parameter of type "const char*"

我该怎么办?(我最近开始学习C所以请用简单的方式回答我)

标签: cstring

解决方案


在您的函数中,参数s1s2char表示单个字符的类型。为了使它们成为字符串,它们必须是字符数组。所以

char cat (char s1[], char s2[]){

或者

char cat (char *s1, char *s2){

代替

char cat (char s1, char s2){

在此更正之后,sprintf()如果目标字符串足够大,您就可以使用

sprintf(s3, "%s%s", s1, s2);

在你的程序中,

s3分配在堆栈上,因为它是一个自动变量

当程序控制退出该cat()功能时,它会超出范围。如果您确实需要返回字符串,请使用s3在堆上分配内存malloc()并返回指向该内存的指针,如

char* cat (char s1[], char s2[]){
    char *s3 = NULL;
    if( (s3=malloc(sizeof(char)*( strlen(s1)+strlen(s2)+1 )))==NULL )
    {
            perror("Not enough memory");  
            return NULL;
    }
    sprintf(s3, "%s%s", s1, s2);
    return s3;
}

或在调用函数中创建字符s3数组并将其传递给cat()

char s3[200];
cat(s3, s1, s2);

........

void cat (char s3[], char s1[], char s2[]){
    if( strlen(s1) + strlen(s2) < 200 )//where 200 is the size of s3
    {
        sprintf(s3, "%s%s", s1, s2);
    }
    else
    {
        printf("\nInput strings too large");
    }
}

请参阅从函数返回 C 字符串


推荐阅读