2014-12-04 49 views
0

我想使用指針來顛倒字符串。我得到一個分段錯誤!有關於此的任何想法? 詳情在代碼中。順便說一句,這是實現這個東西的正確方法嗎?使用數組和指針都顛倒字符串

謝謝,

Gerhard!

我的代碼:

void copy_and_reverse(char* output, char* input) { 

int c = 0; 
int len = 0; 
char *begin; 
char *last; 

len = strlen(input); 
len -= 1; 

begin = input; 
last = output; 

for (c = 0; c < len; c += 1) { 
    last += 1; 
} 

len += 1; 

for (c = 0; c < len; c +=1, begin += 1, last -= 1 { 
temp = *begin; 
*last = *begin; // Here is my problem. Why am I not allowed to access this storage? I have no Idea about that! 
} 
} 

int main(int argc, char **argv) { 

int i = 0; 
int leng = 0; 
char *input[999] = {0}; // input gets the string of the argument, the string should stay in the right order 
char *output[999] = {0}; // output should get the reversed string 



if (argc == 1) { 
    printf("Too few arguments."); 
    return -1; 
} 

for (i = 0; i < argc; i += 1, argv += 1) { 
    if (strlen(*argv) > 100) { 
     printf("Maximum string length exceeded."); 
     return -2; 
    } 
} 
argv -= i; //Unnecessary stuff 
*argv += 1; 
argv += 1; 
argc -= 1; 


for (i = 0; i < argc; i += 1, argv += 1) { 
    *input = *argv; 
    copy_and_reverse(*output, *input); 
} 

return 0; 
} 

回答

0

您聲明:

void copy_and_reverse(char* output, char* input); 

,但你在呼喚:

copy_and_reverse(*output, *input); 

其中

char *input[999] = {0}; 
char *output[999] = {0}; 

換句話說,您已經定義一個999點的數組你可能想要的東西,而不是一串999個字符的項目。

問題是你將output []的第一個元素初始化爲0,所以* output == 0,換句話說,你傳遞一個NULL指針到copy_and_reverse()。當你試圖引用你得到分段錯誤。

什麼你真正需要的是:

char input[999] = {0}; 
char output[999] = {0}; 

copy_and_reverse(output, input); 

,你應該沒問題。

像@Mike S.提到的粘貼代碼還有其他問題,但我相信這些複製粘貼的疏忽。

+0

如果它像thischar輸入[999] = {0}; char output [999] = {0}; ..我怎麼能給數組的參數(字符串)?沒有機會這樣做:* input = * argv; ,不是嗎? – MrShow 2014-12-04 12:12:38

+0

哦,是的,你可以,當定義字符輸入[999]; * input *實際上是一個(char *),所以你可以把它看作是一個指針。當使用[]運算符時,比如輸入[3],它就是*(input + 3)的等價性。另外,要考慮到@Mike S.提出的要點!!! – kostas 2014-12-04 12:20:13

0

發現一些問題,這不會解決你的問題......

1)有了這個

for (c = 0; c < len; c += 1) { 
    last += 1; 
} 

你得到指針 「最後一個」 集以字符串結束。順便說一下,這個循環是無用的 - 更簡單的將是last = output + len;

2)你沒有宣佈「臨時」變量。你如何編譯這段代碼?然後,臨時變量不使用..

3)可能是主要問題之一! - 您輸入爲指向字符串的指針數組。您可能希望有字符(也稱爲串)的陣列 - 所以不要使用char * array[999]char array[999]

3)爲什麼你有if (strlen(*argv) > 100)長度999的陣列?

4)*input = *argv;無效。修復char數組的oyur定義後,它應該是input = * argv。當然,你不需要這樣做,只需撥打function(*argv)即可。最好是function[argv[1]]或什麼。

5)有一段時間C語言的基礎知識,不要忘記看指針,數組和const關鍵字。

有一個愉快的一天