2011-08-23 36 views
1

我有一個連接兩個常量char *並返回結果的函數。我想,雖然做的是加入一個字符一個常數的char *如如何將char加入常量char *?

char *command = "nest"; 
char *halloween = join("hallowee", command[0]); //this gives an error 

char *join(const char* s1, const char* s2) 
{ 
    char* result = malloc(strlen(s1) + strlen(s2) + 1); 

    if (result) 
    { 
      strcpy(result, s1); 
      strcat(result, s2); 
    } 

    return result; 
} 

回答

4

您編寫的函數需要兩個C字符串(即兩個const char *變量)。在這裏,你的第二個參數是command[0],它不是一個指針(const char *),而是一個簡單的'n'字符(const char)。但是,該函數認爲,您傳遞的值是一個指針,並嘗試查找由字母'n'的ASCII值給出的內存地址中的字符串,這會導致出現問題。

編輯:爲了讓它工作,你就必須改變join功能:

char *join(const char* s1, const char c) 
{ 
    int len = strlen(s1); 
    char* result = malloc(len + 2); 

    if (result) 
    { 
      strcpy(result, s1); 
      result[len] = c;   //add the extra character 
      result[len+1] = '\0'; //terminate the string 
    } 

    return result; 
} 
+0

好,我明白,我可以改變這個函數需要的參數,但仍,的strcpy( )和strcat()需要canst char * ..而我擁有的是一個簡單的char。所以我需要做一些命令[0],所以我可以使用它與strcpy()和strcat()。謝謝 – user870565

+0

抱歉,沒有刷新我的網頁。讓我看看你編輯 – user870565

+0

謝謝,我想避免改變函數本身,因爲我用它在其他地方加入兩個常量字符*。所有相同的謝謝,我只是爲此目的創建另一個。 :-) – user870565

2

如果你想加入一個字符,你將不得不編寫一個單獨的函數,它字符的數量從s2追加。

1

最好是創建一個允許添加單個字符的字符串的新功能。 但是,如果你想使用join()功能,因爲它是出於某種原因,你也可以進行如下操作:

char *command = "nest"; 
char *buffer = " "; // one space and an implicit trailing '\0' 
char *halloween; 

*buffer = command[0]; 
halloween = join("hallowee", buffer);