使用函数连接 C 字符串

标签 c

我只想使用函数连接两个字符串和一个分隔符。 但在 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/

相关文章:

c - 在 C 中对 char 使用模运算符

C - 从文件中读取句子到 malloc 创建的字符串数组中

c - 如何将 C 字符串中的计数器变量赋予函数

C - unsigned int 变负 (-ve)

c - 防止过多的 LoadLibrary/FreeLibrary

收集 2 : fatal error: ld terminated with signal 11 [Segmentation fault]

C - 分段故障核心转储?

c - 是否有编译器功能可以注入(inject)自定义函数进入和退出代码?

c++ - 如何将鼠标移动的模拟操作发送到 UE4 应用程序

c - 如何以编程方式获取 Linux 进程的堆栈起始地址和结束地址?