Rectangle 27 0

string reverse with loop and array in c?


b[j]='\0'; // add this
printf("array is %s",b);
return 0;
for(int i=p-1;i>=0;i--){
int i,j;
for (i=p-2, j=0; i>=0; i--,j++) {
    b[j]=a[i];
}
b[j]='\0';
printf("array is %s",b);

1) In your first for loop, you have to reach 0 (i>=0)

2) The a[p-1] contains the null termination('\0') of your string a[]. And the null termination should not be included in the array reverse procedure. So in your first loop you should start from p-2 and not from p-1.

3) And as said in the other answers, you have to use only one loop and not 2 loops.

And after finishing the reversing you have to add a '\0' (null terminator) at the end of your b array

Note
Rectangle 27 0

string reverse with loop and array in c?


#include<stdio.h>

int main(){

char str[] = "str to rev";
char revstr[12]={'\0'};
int i, j;
int length = strlen(str);
j = 0;
for(i = length-1; i>=0; i--){
  revstr[j] = str[i];
  j = j + 1;
}

printf("%s", revstr);

return 0;
}

@Anishsane: the person don't want to use built in function so he can make up his own version of myStrLen I believe

What is myStrLen? You should define that as well, else this code will not link.

Note