繁体   English   中英

Linux 上的 C 程序中的 output 无效

[英]Invalid output in C program on Linux

我正在 Ubuntu 上的 C 上编写类似的程序。 任务是在控制台上显示 output。 我正在使用 gcc 编译器。 任务是得到这样的 output 12, Name Surname, 36, my lapt, -11 ,但我得到12, apt, 36, my lapt, -11 我知道我的程序正在覆盖a at strncat(d, c, 4); ,但我不知道原因。

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

int main()
{
char a[] = "Name";
char b[] = "Surname";
strcat(a, b);
int x = strlen(a);
int y = strcmp(b, a);
char d[] = "my ";
char c[] = "laptop";
strncat(d, c, 4);
int z = strncmp(a, c, 2);
printf("%d, %s, %d, %s, %d\n", x, a, y, d, z);
return 0;
}
char a[] = "Name";
char b[] = "Surname";
strcat(a, b);

是错的。 a没有房间。 它的大小只有 5。这会起作用:

char a[20] = "Name"; // 20 is arbitrary, but it's big enough for the strcat
char b[] = "Surname";
strcat(a, b);

d数组也是如此

这可以在文档中阅读

char * strcat ( char * destination, const char * source );

[参数destination是a]指向目标数组的指针,它应该包含一个C字符串,并且足够大以包含连接的结果字符串。

始终阅读您正在使用的功能的文档。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM