Reputation: 103
The problem is to reverse all the strings in an array of pointers to strings. I wrote the following code for the same. After showing the entered strings the code is not able to reverse the strings. I have tried changing el
and el2
character pointers to characters also, but to no use. Please help me with this.
#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;
}
Upvotes: 0
Views: 70
Reputation: 144695
Performing string reversal in place in your main()
function is cumbersome and error prone. You should instead write a simple function and use it:
Here is a corrected and simplified version:
#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;
}
Upvotes: 1
Reputation: 31306
You're not changing anything. I'd recommend using a swap function:
void swap(char *a, char *b)
{
char tmp = *a;
*a = *b;
*b = tmp;
}
And then in the inner loop:
for(j=0;j<=(len-2)/2;j++)
{
swap(strings[i] + j, strings[i]+(len -j-1));
}
Upvotes: 1
Reputation: 60058
You're swapping local pointer variables, which is pointless.
You need to swap the char
s the pointers point to:
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;
}
Upvotes: 1