你處於未定義行爲的境界。更具體地講,它是什麼做的是這樣的:
char a[] = "AT";
char x[] = "KA";
char y = 'X';
s = strcat(a, "+CMGF="); // a is a constant string, so this is NOT fine. You should be calling s = strcat(s, a) and then s = strcat(s, "+CMGF=")
s = strcat(s, "\r\n"); // "\r\n" = "\r\n\0", so it is also fine
s = strcat(s, &y); // y is a char, and is NOT null-terminated, so it is NOT fine
正巧您使用放置y
和記憶的部分x
並排編譯器,所以strcat
運行,直到它找到的第一個空終止子。所有這一切都假設s
有足夠的空間分配給它來保存所有這些連接(如果沒有,則處於另一個未定義行爲的領域)。
要糾正你的所有已知問題:
char s[100] = {0}; // showing declaration of s of sufficient size
char a[] = "AT";
char x[] = "KA";
char y[] = "X";
sen(s); // shows empty string
s = strcat(s, a); // append a to empty s
s = strcat(s, "+CMGF="); // append "+CMGF=" to the end of new s
sen(s); // will now show "AT+CMGF="
s = strcat(s, "\r\n"); // add "\r\n"
sen(s); // will now show "AT+CMGF=\r\n"
s = strcat(s, y); // append y
sen(s); // will now show "AT+CMGF=\r\nX"
你不確定的行爲。你的程序做什麼不應該擔心。 – chris
這顯然是一個未定義的行爲 –
您已經分配了大小爲3的數組,並且它們的級聯超出了它所能容納的範圍。這對於未定義的行爲至關重要。 – legends2k