+ 1

Please tell me the error in this code.

#include<stdio.h> char* reverse(char*); int main() { printf("%s",reverse("Computer")); return 0; } char* reverse(char *p) { int l,i; char ch; for(l=0; *(p+l)!='\0'; l++); for(i=0; i<l/2; i++) { ch=*(p+i); *(p+i)=*(p+l-1-i); *(p+l-1-i)=ch; } return(p); } Question:I made this program to reverse the string using pointer but it shows an error can anyone tell me the error in this code please.

9th Sep 2020, 5:31 PM
Samir Singh
Samir Singh - avatar
2 Answers
+ 5
#include<stdio.h> void reverse(char*); // void return type is enough because we are passing the pointer so changes automatically happen int main() { char st[] = "Computer"; reverse(st); printf("%s",st); return 0; } /* +---+---+---+---+---+---+---+---+ | C | o | m | p | u | t | e | r | +---+---+---+---+---+---+---+---+ | | a points to 0 b points to length-1 a++ from C -> o -> m -> p b-- frim r -> e -> t -> u On the process the value of "a" and "b" get swap.*/ void reverse(char *p) { int l,i; char ch; char *a, *b; a = p; // pointing to the string b = p; // pointing to the string for(l=0; *(p+l)!='\0'; l++); b = (p+l-1); // pointing to the last element of the string for(i=0; i<l/2; i++) { ch=*b; *b=*a; *a=ch; a = (p+(i+1)); // or a++; b = (p+l-1-(i+1)); // or b--; } }
9th Sep 2020, 6:11 PM
minirkk
minirkk - avatar
+ 3
Haven't tested the code yet, but just looking through it there is a semicolon directly after the closing parenthesis of the first for loop. This means that that for loop has no body. for(l=0; *(p+1)!='\0'; l++); <--- remove semicolon
9th Sep 2020, 5:49 PM
ChaoticDawg
ChaoticDawg - avatar