问题是要反转指向字符串的指针数组中的所有字符串。我为相同的代码编写了以下代码。显示输入的字符串后,代码无法反转字符串。我尝试将el
和el2
字符指针也更改为字符,但没有用。请帮助我。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
int x, i, length, len, j;
printf("How many strings you want to enter:\n");
scanf("%d", &x);
char *strings[x], string[50], *p, *t, *el, *el2;
for (i = 0; i < x; i++) {
scanf(" %49[^\n]", string);
length = strlen(string);
p = (char *)malloc(length + 1);
strcpy(p, string);
strings[i] = p;
}
printf("Entered strings are:\n");
for (i = 0; i < x; i++) {
printf("%s\n", strings[i]);
}
printf("Reversed strings :\n");
for (i = 0; i < x; i++) {
len = strlen(strings[i]);
for (j = 0; j <= (len - 2) / 2; j++) {
el = (strings[i] + j);
el2 = (strings[i] + (len - j - 1));
t = el2;
el2 = el;
el = t;
}
}
for (i = 0; i < x; i++) {
printf("%s\n", strings[i]);
}
return 0;
}
答案 0 :(得分:1)
您正在交换局部指针变量,这毫无意义。
您需要交换指针指向的char
s:
for(j=0;j<=(len-2)/2;j++)
{
char t, *el, *el2;
el = (strings[i] + j);
el2 = (strings[i]+(len -j-1));
t = *el2;
*el2 = *el;
*el = t;
}
答案 1 :(得分:1)
您没有更改任何内容。我建议使用交换功能:
void swap(char *a, char *b)
{
char tmp = *a;
*a = *b;
*b = tmp;
}
然后进入内循环:
for(j=0;j<=(len-2)/2;j++)
{
swap(strings[i] + j, strings[i]+(len -j-1));
}
答案 2 :(得分:1)
在main()
函数中执行字符串反转很麻烦且容易出错。相反,您应该编写一个简单的函数并使用它:
以下是经过纠正和简化的版本:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *str_reverse(char *s) {
for (size_t i = 0, j = strlen(s); i < j--; i++) {
char t = s[i];
s[i] = s[j];
s[j] = t;
}
return s;
}
int main() {
int x, i;
printf("How many strings you want to enter:\n");
if (scanf("%d", &x) != 1 || x <= 0 || x > 1000) {
printf("Invalid number: %d\n", x);
return 1;
}
char *strings[x], string[50];
for (i = 0; i < x; i++) {
if (scanf(" %49[^\n]", string) != 1) {
printf("Premature end of file\n");
return 1;
}
// use strdup to allocate string copies.
// strdup is a Posix standard function
// if your system does not have it, it is easy to implement.
strings[i] = strdup(string);
}
printf("Entered strings are:\n");
for (i = 0; i < x; i++) {
printf("%s\n", strings[i]);
}
// Reverse strings
for (i = 0; i < x; i++) {
str_reverse(strings[i]);
}
printf("Reversed strings:\n");
for (i = 0; i < x; i++) {
printf("%s\n", strings[i]);
}
return 0;
}