问题
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