char * return (null) from a function in C [duplicate]

与世无争的帅哥 提交于 2021-02-17 07:10:23

问题


I was trying to append two const char* from a function but it returns (null). What should I do now? I'm working in VS Code on Ubuntu 20.04 using GCC Compiler v9.3.0.

Code

#include <string.h>
#include <stdio.h>

char *JoinChars(const char *a, const char *b)
{
    char buffer[strlen(a) + strlen(b) + 1];
    strcpy(buffer, a);
    strcat(buffer, b);
    return buffer;
}
int main()
{
    const char *b1 = "Hello\t";
    const char *b2 = "World\n";
    printf("%s", JoinChars(b1, b2));
    return 0;
}

回答1:


You cant return the pointer to the local variable as the variable stops to exist when the function returns. It is Undefined Behaviour. Some compilers when they detect it issue the warning and set the return value to NULL.

You need to allocate memory for the concatenated strings

char *JoinChars(const char *a, const char *b)
{
    char *buff = NULL;
    size_t str1len, str2len;
    if(a && b)
    {
        str1len = strlen(a);
        str2len = strlen(b);
        buff = malloc(str1len + str2len + 1);
        if(buff)
        {
            strcpy(buff, a);
            strcpy(buff + str1len, b);
        }
    }
    return buff;
}

(without the string library functions)

{
    const char *end = str;

    while(*end) end;

    return end-str;
}

char *JoinChars(const char *a, const char *b)
{
    char *buff = NULL;
    size_t str1len, str2len;
    if(a && b)
    {
        str1len = mystrlen(a);
        str2len = mystrlen(b);
        buff = malloc(str1len + str2len + 1);
        if(buff)
        {
            char *wrk = buff;
            while(*a) *wrk++ = *a++;
            while(*b) *wrk++ = *b++;
            *wrk = 0;
        }
    }
    return buff;
}

or caller should provide the buffer large enough to accommodate both strings:

char *JoinChars(char *buff, const char *a, const char *b)
{
    size_t str1len;
    if(buff && a && b)
    {
        str1len = strlen(a);
        strcpy(buff, a);
        strcpy(buff + str1len, b);
    }
    return buff;
}


来源:https://stackoverflow.com/questions/65754213/char-return-null-from-a-function-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!