2017-01-02 52 views
-9

這就是我想要做的,但我的代碼要麼不編譯,要麼給我一個意外的輸出「BC」而不是「B」。如何在C中通過引用傳遞數組?

#include <stdio.h> 

void removeFirstAndLastChar(char** string) { 
    *string += 1; // Removes the first character 
    int i = 0; 
    for (; *string[i] != '\0'; i++); 
    *string[i - 1] = '\0'; 
} 

int main(void) { 
    char* title = "ABC"; 
    removeFirstAndLastChar(&title); 
    printf("%s", title); 
    // Expected output: B 
    return 0; 
} 

我經歷了很多這裏涉及到通過引用傳遞指針答案看了,但他們都不似乎包含我想在我的removeFirstAndLastChar()函數來完成操作。

+3

試圖修改字符串文字的未定義行爲。 – EOF

+1

你應該把'char * title =「ABC」;'改成'char title [] =「ABC」;' – mch

+1

你需要'(* string)[i]'而不是'* string [i]'。 –

回答

2

我不認爲你的算法或C慣例,對你的問題發表評論的朋友是完全正確的。但是如果你仍然這樣做,你可以使用這種方法。

#include <stdio.h> 
#include <string.h> 

void removeFirstAndLastChar(char* string) { 
    memmove(string,string+1,strlen(string)); 
    string[strlen(string)-1]=0; 
} 

int main(void) { 
    char title[] = "ABC"; 
    removeFirstAndLastChar(title); 
    printf("%s", title); 
    // Expected output: B 
    return 0; 
}