C隐式定义中的连接字符串

时间:2014-01-29 23:48:44

标签: c string concatenation

我有一个关于在C中连接两个字符串的问题,说“Ring Ding” 我有一个char * d,我malloc 14 * sizeof(char)只是为了保持安全,最后包含\ o字符,但我的功能仍然是segfaulting,我不知道为什么。它说我无法隐含地定义strcopy。我在想我的问题是我不能只是出来说“戒指”,但我可能会弄错。

char * k = malloc(14*sizeof(char));
strcopy(k, "Ring");
strcat(k, "Ding");
printf("%s\n", k);

3 个答案:

答案 0 :(得分:1)

'strcopy'有一个错字;它通常来自string.h的“strcpy”

由于C允许您在不首先声明函数的情况下调用函数,因此在字符串h中找不到“隐式声明”的警告。

我很惊讶您能够运行程序,因为它应该有一个链接器错误,因为它找不到函数的定义。

如果您修正了拼写错误,它应该编译并运行正常。

我还建议使用这些字符串函数的strl *版本(strlcpy,strlcat等...) - 它更安全;请参阅手册页。

答案 1 :(得分:0)

我希望这段代码可以帮到你!

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

int main()
{
    char * k = (char*)malloc(14*sizeof(char));
    strcpy(k, "Ring");
    strcat(k, "Ding");
    printf("%s\n", k);
    return 0;
}

答案 2 :(得分:0)

假设你有:

char* str1 = "Ring";
char* str2 = "Ding";

请遵循以下步骤(作为一般规则):

// Function 'strlen' always returns the length excluding the '\0' character at the end
// The '+1' is because you always need room for an additional '\0' character at the end
char* k = (char*)malloc(strlen(str1)+strlen(str2)+1);

// Write "Ring\0" into the memory pointed by 'k'
strcpy(k,str1);

// Write "Ding\0" into the memory pointed by 'k', starting from the '\0' character
strcat(k,str2);

// Print the memory pointed by 'k' until the '\0' character ("RingDing") to the console
printf("%s\n",k);

// De-allocate the memory pointed by 'k'
free(k);
相关问题