あなたは未定義の行動の領域にいます。より具体的には、次のことを行っています。
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"