我想使用指針來顛倒字符串。我得到一個分段錯誤!有關於此的任何想法? 詳情在代碼中。順便說一句,這是實現這個東西的正確方法嗎?使用數組和指針都顛倒字符串
謝謝,
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;
}
如果它像thischar輸入[999] = {0}; char output [999] = {0}; ..我怎麼能給數組的參數(字符串)?沒有機會這樣做:* input = * argv; ,不是嗎? – MrShow 2014-12-04 12:12:38
哦,是的,你可以,當定義字符輸入[999]; * input *實際上是一個(char *),所以你可以把它看作是一個指針。當使用[]運算符時,比如輸入[3],它就是*(input + 3)的等價性。另外,要考慮到@Mike S.提出的要點!!! – kostas 2014-12-04 12:20:13