【问题标题】:Concatenating Strings in C Implicit Definition [closed]在 C 隐式定义中连接字符串
【发布时间】:2014-01-29 23:48:43
【问题描述】:

我有一个关于在 C 中连接两个字符串以说“Ring Ding”的问题 我有一个 char * d ,我 malloc 14*sizeof(char) 只是为了安全起见,在末尾包含 \o 字符,但我的函数仍然存在段错误,我不知道为什么。它说我不能隐式定义 strcopy。我在想我的问题是我不能出来说“Ring”,但我可能弄错了。

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

【问题讨论】:

  • strcopy 应该是 strcpy。你确定代码有段错误吗?这是一个运行时问题,我希望您的代码无法链接,导致您无法运行任何程序。
  • 只需将其从 strcopy 更改为 strcpy 即可修复!谢谢!
  • 如果您修正了错字,您展示的代码应该可以在没有核心转储的情况下安全运行,除非您事先进行了极端的内存分配并且空间不足。您应该检查内存分配,但假设可行,其余的也应该可以正常工作。所以,如果问题不在这段代码中,它可能在你程序的其他地方——那么你的代码还在做什么呢?
  • 请更新您的问题,以显示一个 完整 程序,该程序显示 seg 错误。正如@simonc 所说,拼写错误的函数名称应该意味着您首先不会获得可执行文件,因此您不会出现段错误。您可以运行从早期版本的源代码生成的可执行文件吗?重新编译前删除可执行文件。

标签: c string concatenation


【解决方案1】:

'strcopy' 有错别字;它通常是 string.h 中的“strcpy”

由于 C 允许您在不先声明函数的情况下调用函数,因此您会收到“隐式声明”的警告,因为它没有找到 int string.h。

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

如果你修正了错字,它应该可以编译并运行良好。

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

【讨论】:

  • 还值得指出的是,strl* 函数是非标准的,可能并非在所有系统上都可用。
  • (关于使用strn* 系列的强制性评论)
【解决方案2】:

假设你有:

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);

【讨论】:

  • 不要转换malloc的结果。
【解决方案3】:

希望这段代码对你有帮助!

#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;
}

【讨论】:

  • void main() 应该是 int main(void)(char*) 演员表是不必要的,也是不好的做法。没有额外解释的代码转储不是一个好的答案。您所做的只是添加所需的 #include 指令和 main 函数并修复拼写错误的函数名称。
猜你喜欢
  • 2013-09-05
  • 2020-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多