【发布时间】:2017-03-12 19:48:18
【问题描述】:
我正在尝试编写必须实现库函数 strncpy、strncat 和 strncmp 版本的代码,但它在运行时给了我 Abort 陷阱:6 错误。任何想法都非常感谢:
#include<stdio.h>
#include<string.h>
int main() {
char str1[400];
printf ("Enter the first string: ");
fgets (str1, 400, stdin);
char str2[400];
printf ("Enter the second string: ");
fgets (str2, 400, stdin);
int num;
printf ("Enter the number: ");
scanf ("%d", &num);
char dest[num];
strncpy(dest, str2, num);
dest[num] = '\0';
printf ("strncpy is %s \n", dest);
int lengthStr1 = strlen (str1);
char str1copy [lengthStr1];
strncpy(str1copy, str1, lengthStr1);
str1copy [lengthStr1] = '\0';
printf ("str1copy is %s \n", str1copy);
strncat(str1copy, dest, num);
printf ("strncat is %s\n", str1copy);
}
我知道我的 strncpy 部分有效。
【问题讨论】:
-
你会在不把车送到车库的情况下让机械师修理你的车吗?你所谓的实现的功能在哪里?
-
dest[num] = '\0';出现越界。str1copy [lengthStr1] = '\0';同上。 -
也许我不太明白它们所说的实施是什么意思。我以为我们只需要使用这些功能。你将如何“实现”一个功能? @StoryTeller
-
return_type func_name(parameters) { statements_to_execute; }是“实现”功能的方式。 -
注意:标准库中定义的名称是保留的。你不能在你的代码中定义它们,也不能用不同的签名重新声明它们。