您处于未定义行为的领域。更具体地说,它正在做的是:
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"