简体   繁体   中英

reversing the string without any predefined function in c

i am using below code, i don't knw what i doing wrong.

#include <stdio.h>
void main()
{

    char a[5];
    char ptr[5] = "hello";
    int i,j,k=0;

    for(i=0;ptr[i] !='\0'&&ptr[i]!=' ';i++){}
    k=i;
    for(j=0;j<=i;j++)
    {
        a[j] = ptr[k];
        printf("%c %c %d %d %d\n",a[j],ptr[k],i,j,k);
        k--;
    }
    printf("%s %s",a,ptr);
}

Output:

  5 0 5
o o 5 1 4
l l 5 2 3
l l 5 3 2
e e 5 4 1
h h 5 5 0
 hello

I suppose this is what you're looking for.

#include <stdio.h>
int main()
{

    char a[6];
    char ptr[6] = "hello";
    int i,j,k=0;

    for(i=0;ptr[i] !='\0'&&ptr[i]!=' ';i++){}
    k= i - 1;
    for(j=0;j<i;j++)
    {
        a[j] = ptr[k];
        printf("%c %c %d %d %d\n",a[j],ptr[k],i,j,k);
        k--;
    }
    printf("%s %s",a,ptr);
}

I have edited my answer for undefined length of input string. Have a look:

#include <stdio.h>
#include<string.h>

void main(){
    char a[10];
    char ptr[10];

    scanf("%s", ptr);

    for(int i = 0, j = strlen(ptr)-1; j != -1; i++, j--){
        a[i] = ptr[j];
    }
    printf("%s", a);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM