[英]Invalid output in C program on Linux
I'm writing a similar program on C on Ubuntu.我正在 Ubuntu 上的 C 上编写类似的程序。 The task is to show the output on console.
任务是在控制台上显示 output。 I am using gcc compiler.
我正在使用 gcc 编译器。 The task is to get such an output
12, Name Surname, 36, my lapt, -11
, but instead i get 12, apt, 36, my lapt, -11
.任务是得到这样的 output
12, Name Surname, 36, my lapt, -11
,但我得到12, apt, 36, my lapt, -11
。 I know that my program is overwriting a
at strncat(d, c, 4);
我知道我的程序正在覆盖
a
at strncat(d, c, 4);
, but i don't know the reason why. ,但我不知道原因。
#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);
is wrong.是错的。
a
does not have room. a
没有房间。 It's size is only 5. This would work:它的大小只有 5。这会起作用:
char a[20] = "Name"; // 20 is arbitrary, but it's big enough for the strcat
char b[] = "Surname";
strcat(a, b);
Same goes for the d
array d
数组也是如此
This can be read in documentation这可以在文档中阅读
char * strcat ( char * destination, const char * source );
[The parameter
destination
is a] Pointer to the destination array, which should contain a C string, and be large enough to contain the concatenated resulting string.[参数
destination
是a]指向目标数组的指针,它应该包含一个C字符串,并且足够大以包含连接的结果字符串。
Always read the documentation for functions you're using.始终阅读您正在使用的功能的文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.