I want to reverse a string in the C language. I’m kinda new, so I would love to get some help and explanation. Why doesn’t my solution work?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
char *rev(char *str) {
char *q = str;
int len = strlen(str);
char *p = (char*)calloc(len+1, sizeof(char));
int j=0;
if (NULL == str || len == 1) return str;
for (j = len+1 ; j > 0 ; j-- ) {
p[j]=*q;
q++;
}
return p;
}
int main(int argc, char **argv){
char *t = argv[1];
char *p ;
printf("%s",t);
p=rev(t);
printf("%s",p);
getchar();
return 0;
}
It’s not working 🙁
You have to be careful with your indices at the boundaries.
One way to fix is replace your
forline with this: