2017-01-02 44 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; 
}