除了缺少格式字符串也出現了一些其他問題:
char* key;
key = malloc(100); // Don't cast return value of malloc in C
// Always check if malloc fails
if(key) {
memset(key, '\0' , 100 * sizeof(char));
const char * skey = "844607587"; // Use const with constant strings
const char * mess = "hello world";
// sprintf requires format string like printf
// Use snprintf instead of sprintf to prevent buffer overruns
snprintf(key, 100, "%s%s", skey, mess);
printf("%s", key);
free(key);
}
編輯:
版本與calloc
將取代malloc
並刪除memset
:
key = calloc(100, sizeof(char));
if(key) {
const char * skey = "844607587";
您自動覆蓋的最後一個值'sprintf的(鍵,亂七八糟);' –
儘管意大利麪條,有可能(有時是必要的)使用'鍵+的strlen(SKEY) '作爲第二個'sprintf'的目的地。請注意,如果你不知道自己在做什麼,我說你*可以**,**不**,應該**,**。 – Jite
也更好用'snprintf' –