简体   繁体   English

在我使用strcat函数时发现错误

[英]Finding the error in my use of the strcat function

Please help me i can't solve this question i've got in university. 请帮助我,我无法解决我上大学时遇到的这个问题。 I asked in our university forum and they said this clue: "what is the difference if you send a long string to strcat, or you send the string B? " 我在我们的大学论坛上问,他们说了这条线索:“如果将长字符串发送给strcat或发送字符串B,有什么区别?”

Explain what is wrong with the next program: 解释下一个程序出了什么问题:

#include <string.h>
#include <stdio.h>
int main()
{
    char A[10];
    char B[20];
    strcpy(A, "A student");
    strcpy(B, "fail the exam");
    printf("%s\n", strcat(A, B));
    return 0;
}

The first parameter of strcat must be large enough to contain the concatenated resulting string. strcat的第一个参数必须足够大以包含连接的结果字符串。 So change it to : 因此将其更改为:

char A[30];

or you will probably get a segmentation fault. 否则您可能会遇到细分错误。

See "A student fail the exam" is large than 10 . 看到“学生考试不及格” 大于10

So at least use char A[24] instead of char A[10] 因此,至少要使用char A[24]而不是char A[10]

Because strcat(s,t) concatenates t to the end of s, s must be large enough to hold the new, concatenated string. 由于strcat(s,t)将t连接 s 的末尾 ,因此s必须足够大以容纳新的连接字符串。 It returns a pointer to the first character in s. 它返回一个指向s中第一个字符的指针。

Array A should be large enough to hold the contents of array B other wise strcat behaviour is unpredictable , segmentation fault may occur, Application may get crash.Refer the link below. 数组A应该足够大以容纳数组B的内容,否则strcat行为不可预测 ,可能会发生分段错误,应用程序可能会崩溃。请参阅下面的链接。 [Link] http://linux.die.net/man/3/strcat [链接] http://linux.die.net/man/3/strcat

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

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