我想使用指针反转字符串。我遇到段错误!对此有什么想法吗? 详细信息在代码中。顺便问一下,这是实现这个东西的正确方法吗?
谢谢,
格哈德!
我的代码:
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;
}
最佳答案
您声明:
void copy_and_reverse(char* output, char* input);
但你正在打电话:
copy_and_reverse(*output, *input);
哪里
char *input[999] = {0};
char *output[999] = {0};
换句话说,您定义了一个包含 999 个指向 char 项的指针的数组,而不是您可能想要的包含 999 个 char 项的字符串。
问题是你将output[]的第一个元素初始化为0,因此*output == 0,换句话说,你将NULL指针传递给copy_and_reverse()。当您尝试引用时,您会遇到段错误。
您真正需要的是:
char input[999] = {0};
char output[999] = {0};
和
copy_and_reverse(output, input);
你应该没问题。
粘贴的代码还存在其他问题,如 @Mike S. 提到的,但我相信这些复制粘贴的疏忽。
关于c - 使用数组和指针反转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27292457/