Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inverse String in c

Tags:

c

string

i've done a function that inverse a String(array of character) given in parameter , but it's not working , any idea why ?

I'm getting something like this : æIGt(Kt$0@

thanks you

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

char *
inverse(char *s)
{
    int i, taille = strlen(s);
    char r[taille];
    for (i = 0 ; i < taille ; i++)
    {
        r[i] = s[taille - i - 1];
    }
    r[i] = '\0';    
    return r;
}

int
main()
{    
    char s[] = "kira";
    char *r = inverse(s);

    printf("%s",r);

    return 1;
}
like image 735
Amar Bessalah Avatar asked Jul 28 '26 01:07

Amar Bessalah


2 Answers

You are returning a pointer to a local variable. That variable gets destroied when the function inverse returns, so accessing the pointer after the function exits will return invalid data.

like image 67
Gabor Sipkoi Avatar answered Jul 30 '26 07:07

Gabor Sipkoi


It's slightly hard to tell from you question, because you haven't given any outputs, but my best guess is that it's because your returning a pointer to an item on the stack, which will get over-written by the next call, in your case printf. You need to pass inverse a place to put its answer. Try this instead:

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

void inverse(char *s, char *r)
{
    int i,taille=strlen(s);


    for(i=0;i<taille;i++)
    {
        r[i]=s[taille-i-1];
    }
    r[i]='\0';
}



int main()
{

char s[] = "kira";
char r[sizeof(s)];

inverse(s, r);    

printf("%s",r);

return 1;
}
like image 42
Alastair Brown Avatar answered Jul 30 '26 09:07

Alastair Brown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!