因此,我开始学习C(来自Java)并尝试自行实现concat
函数
到目前为止,我有这个:
#include <stdlib.h>
#include <string.h>
char* concat(char *first, char *second) {
size_t f = strlen(first);
size_t s = strlen(second);
char ret[f+s+1];
for(int i = 0; i < f ; i++){
ret[i] = *first++;}
for(int a = 0; a < s; a++){
ret[f+a] = *second++;}
ret[f+s] = '\0';
printf("%s\n",ret);
return ret;
}
int main(int argc, char **argv) {
printf("%s",concat("test","test2"));
}
这将两次打印结果“ testtest2”
但是,如果我删除printf
中的concat
行,则printf
中的main
将不再打印任何内容。有点困惑。
答案 0 :(得分:0)
程序具有未定义的行为,因为该函数返回具有自动存储持续时间的本地声明的数组的指针。退出该函数后,该数组不再存在。
您必须动态分配内存。
例如
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * concat( const char *s1, const char *s2 )
{
char *result = malloc( strlen( s1 ) + strlen( s2 ) + 1 );
if ( result != NULL )
{
char *p = result;
while ( ( *p = *s1++ ) ) ++p;
while ( ( *p = *s2++ ) ) ++p;
}
return result;
}
int main( void )
{
char *result = concat( "test", "test2" );
puts( result );
free( result );
}
程序输出为
esttest2