2013-10-08 18 views
0
char* key; 

key=(char*)malloc(100); 

memset(key,'\0',100*sizeof(char)); 
char* skey="844607587"; 

char* mess="hello world"; 


sprintf(key,skey); 

sprintf(key,mess); 
printf("%s",key); 
free(key); 

爲什麼打印輸出只有「混亂」沒有skey?有沒有其他的方式來使用C結合兩個字符串?爲什麼我不能將兩個字符串組合在一起?

+1

您自動覆蓋的最後一個值'sprintf的(鍵,亂七八糟);' –

+1

儘管意大利麪條,有可能(有時是必要的)使用'鍵+的strlen(SKEY) '作爲第二個'sprintf'的目的地。請注意,如果你不知道自己在做什麼,我說你*可以**,**不**,應該**,**。 – Jite

+0

也更好用'snprintf' –

回答

3
sprintf(key,"%s%s",skey,mess); 

分別爲它們添加:

sprintf(key,"%s",skey); 
strcat(key, mess); 
+0

怎麼樣一個接一個,不能同時梳理 –

+0

不幸的是不是sprintf ..因爲它會覆蓋。 – sukhvir

+1

@SongZhibo因爲你用鍵值 –

1

您正在使用sprintf兩次在同一個緩衝,所以它被覆蓋。

您可以使用strcat這樣的:

strcpy(key, skey); 
strcat(key, mess); 
1

sprintf(key,skey);

它寫入skeykey

sprintf(key,mess); 

它寫入messkey,覆蓋先前寫skey

所以,你應該這樣做:

sprintf(key,"%s%s", skey, mess); 
1
printf("Contcatened string = %s",strcat(skey,mess)); 
1

除了缺少格式字符串也出現了一些其他問題:

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"; 
+0

同樣使用'calloc'來獲得已經歸零的內存 – mvp

+0

@mvp真,如果可用,最好使用'calloc'。 – user694733

0

你的代碼如下

sprintf(key,skey); 
sprintf(key,mess); 
printf("%s",key); 

結果將是 「世界你好」

您可以更改代碼如下

sprintf(key, "%s%s", skey, key); 
printf("%s",key); 

結果作爲遵循「844607587hello world」

0

代碼如下:

strncpy(key, skey, strlen(skey)); 
strcat(key, mess); 
相關問題