我只想使用函数连接两个字符串和一个分隔符。 但在 main() 中我没有得到连接的字符串。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* PathCreation(char* Str1, char* Str2, char* Separator=(char*)"/"){
char CreatedPath[strlen(Str1)+strlen(Str2)+strlen(Separator)+1];
strncpy(&CreatedPath[0], Str1, strlen(Str1));
strncpy(&CreatedPath[strlen(Str1)], Separator, strlen(Separator));
strncpy(&CreatedPath[strlen(Str1)+1], Str2, strlen(Str2));
CreatedPath[strlen(Str1)+strlen(Str2)+1]='\0';
//printf("\n%s", CreatedPath);
return CreatedPath;
}
int main(void)
{
char str1[] = "foo";
char str2[] = "bar";
char* ccat=PathCreation(str1, str2);
puts(str1);
puts(str2);
puts(ccat);
}
最佳答案
由于您一直在使用 C 风格进行编程,所以我将坚持使用 C 风格。但我应该指出,由于默认参数,您的代码仅在 C++ 中有效。
问题是,当您简单地声明将其分配给堆栈的内容时,一旦函数退出,堆栈就会被销毁,并且在堆栈被销毁后尝试使用数据是未定义的行为,这意味着代码可能会工作有时正如您所期望的那样,但它最终也可能指向垃圾或只是崩溃。
相反,您需要在堆上分配它,以便在函数退出后它仍然存在。将分配字符串的行替换为:
char* CreatedPath = (char*)malloc(sizeof(char)*(strlen(Str1)+strlen(Str2)+strlen(Separator)+1));
关于使用函数连接 C 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56199936/