R – C: problem with char*

cpointers

/*
 * code.c
 *
 * TASK
 *      Reverse a string by reversing pointers. Function should use return
 *      type char* and use a char* parameter as input.
 */
#include <stdio.h>
#include <string.h>
#define STRMAX 51

char* reverse(char* sPhrase[]);

int main() {
    char sPhrase[STRMAX];
    char sReverse[STRMAX];
    printf("Enter string (max. 50 chars): ");
    gets(sPhrase);
    sReverse = reverse(sPhrase);

    return 0;
}

char* reverse(char* sPhrase[]) {
    char* sOutput[STRMAX];
    int iCnt = 0, iCntRev;

    for (iCntRev = strlen(*sPhrase)-2; iCntRev >= 0; iCntRev--) {
        sOutput[iCnt] = sPhrase[iCntRev];
        iCnt++;
    }

    *sOutput[iCnt] = '\0';      // Don't forget to close the string

    return sOutput;
}

This code has some quirks:

  • sReverse = reverse(sPhrase);

    • [Error] incompatible types in assignment
    • [Warning] passing arg 1 of `reverse' from incompatible pointer type
  • return sOutput;

    • [Warning] function returns address of local variable
    • [Warning] return from incompatible pointer type

What do these warnings mean? How can I patch the errors? The function should keep char* as a return type and as a parameter since I'm making this little program as part of a C training course.

Best Answer

I see a few problems. First of all, char* sOutput[STRMAX] is an array of char*'s - presumably you meant char sOutput[STRMAX]?

Secondly, and more importantly, when you declare an array in a function in that way (char sOutput[STRMAX]), it gets allocated on the stack and deallocated when the function returns. Thus, if you try to return it, you'll get undefined results, because it's not technically supposed to exist anymore!

The solution is to pass a buffer into the function for it to use:

char* reverse(char const sPhrase[], char sOutput[])

(I added the const so you don't accidentally overwrite sPhrase). Then call reverse like this:

reverse(sPhrase, sReverse);

Now as for whether your algorithm works...

Related Topic