Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing a string in C using pointers?

Tags:

c

string

reverse

Language: C

I am trying to program a C function which uses the header char *strrev2(const char *string) as part of interview preparation, the closest (working) solution is below, however I would like an implementation which does not include malloc... Is this possible? As it returns a character meaning if I use malloc, a free would have to be used within another function.

char *strrev2(const char *string){
    int l=strlen(string);
    char *r=malloc(l+1);
    for(int j=0;j<l;j++){
        r[j] = string[l-j-1];
    }
    r[l] = '\0';
    return r;
}

[EDIT] I have already written implementations using a buffer and without the char. Thanks tho!

like image 559
Edward Yang Avatar asked Dec 21 '22 08:12

Edward Yang


1 Answers

No - you need a malloc.

Other options are:

  • Modify the string in-place, but since you have a const char * and you aren't allowed to change the function signature, this is not possible here.
  • Add a parameter so that the user provides a buffer into which the result is written, but again this is not possible without changing the signature (or using globals, which is a really bad idea).
like image 88
Mark Byers Avatar answered Dec 24 '22 01:12

Mark Byers