简体   繁体   中英

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? "

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. 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 .

So at least use char A[24] instead of 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. It returns a pointer to the first character in s.

Array A should be large enough to hold the contents of array B other wise strcat behaviour is , segmentation fault may occur, Application may get crash.Refer the link below. ,可能会发生分段错误,应用程序可能会崩溃。请参阅下面的链接。 [Link] http://linux.die.net/man/3/strcat

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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