簡體   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