I'm trying to solve a piece of code a friend sent me. He's practicing pointers and is trying to reverse a string using them.
It should be a pretty simple task, but there's just a gap in my knowledge here. I've been able to successfully create a for loops which iterates through the string properly using i
and j
as control variables. I've been able to print out the characters as well, which need to be swapped.
The only problem is that commented line of code in the for loop. It's supposed to be swapping the two values, but is throwing an error, and I don't get why.
#include <stdio.h>
int length(char *p);
void reverse(char *);
int main() {
char *p = "Computer";
reverse(p);
}
int length(char *p) {
int i;
for (i = 0; *(p + i) != '\0'; i++);
return i;
}
void reverse(char *p) {
int l, i;
char t;
for (l = 0; *(p + l) != '\0'; l++);
int len = l;
int temp;
for (i = 0; i < l; i++, l--) {
t = *(p + i);
printf("i-th element - %c\n", t);
printf("j-th element - %c\n", *(p + len - 1 - i));
*(p + i) = *(p + len - 1 - i); // crash
}
puts(p);
}
I'm not even sure it's possible to swap them this way. I would have gone with the t = p[i]; p[i] = p[i + 1]...
approach. If anyone can correct and explain this and the pointer related drama, that would be great.
Firstly, you must not try to modify string literals.
You should use an (modifiable) array:
char p[] = "Computer";
instead of
char *p = "Computer";
Secondly, you will need
*(p + len - 1 - i) = t;
after
*(p + i) = *(p + len - 1 - i);
to complete the swapping.