附加字符串以返回指针/广播错误的函数

时间:2019-02-23 22:33:12

标签: c function pointers

我正在尝试创建一个函数,该函数接受两个输入字符串dest和src,并将src字符串附加到dest字符串。

以下是我当前拥有的功能。但是,当我尝试使用它时,我 收到一条错误消息,指出“不带强制转换功能而从函数返回'char'”。我知道我的错误涉及return语句以及如何将其用作指针,但是我不确定如何解决它。

char* strcat(char dest[], char src[]) {
    int destL = lenstr(dest);
    int srcL = lenstr(src);
    char result[destL + srcL];

    int i;
    for(i = 0; i < destL; i++){
        result[i] = dest[i];
    }

    for(i = destL; i < destL+srcL; i++){
        result[i] = src[i-destL];
    }

    return *result;
}

lenstr功能是:

int lenstr(char* s) {
    int len = 0;
    while(s[len++] != '\0');
    return len-1;
}

2 个答案:

答案 0 :(得分:1)

You cannot return a locally declared array. Well you can, but the data may be overwritten at any time since it is no longer valid.

What you need to do is something like this:

char* strcat(char dest[], char src[]) {
    char * result = malloc((lenstr(dest)+lenstr(src)+1) * sizeof *result);

    // Code to copy data

    return result;
}

Note that +1 is important to make room for the \0 terminator.

答案 1 :(得分:0)

  

但是,当我尝试使用它时,出现一个错误,指出“从没有强制转换的函数返回'char'”。

此错误仅表示您的返回值与函数声明不匹配。在函数声明中,您提到它返回一个char *。但是,在实际的return语句中,您将返回*result,这是已取消引用的char指针,即char

代码中的第二个问题是您要从函数返回数组。在方法中使用数组分配的内存将对调用方方法不可用。您需要在堆上创建内存并返回一个指向它的指针,然后让调用方在使用后释放内存。

签出以下工作代码:

char* strcat1(char dest[], char src[]) {
    int destL = lenstr(dest);
    int srcL = lenstr(src);

    char * result = malloc(sizeof(char) * (destL + srcL));

    int i;
    for(i = 0; i < destL; i++){
        result[i] = dest[i];
    }

    for(i = destL; i < destL+srcL; i++){
        result[i] = src[i-destL];
    }

    return result;
}

请确保呼叫者释放了结果,如下所示:

char * result = strcat1("hi", "ho");
printf(result);
free(result);