Reversing a string in c with recursion

后端 未结 11 757
遥遥无期
遥遥无期 2021-01-22 09:47

I have written code to reverse a string in c... it works fine but I can\'t return the reversed string in the main() function.

#include

        
11条回答
  •  深忆病人
    2021-01-22 10:21

    Here is another way to reverse a string using recursion:

    void reverseString(char* dest, char *src, int len) {
        if (src == NULL || len == 0)
            return;
    
        reverseString(dest, src + 1, len - 1);
        strncat_s(dest, len + 1, src, 1);
    }
    

    You can call like that:

    #include 
    #include 
    #include 
    
    #define STRING "Let's try this one."
    #define SIZE 20
    
    void main() {
    
        char* src = (char*)malloc(SIZE);
        char* dest = (char*)malloc(SIZE);
    
        strcpy_s(dest, SIZE, "");
        strcpy_s(src, SIZE, STRING);
    
        reverseString(dest, src, strlen(src));
        /* Do anything with dest. */
        // printf("%s\n", dest);
    
        free(src);
        free(dest);
    }
    

提交回复
热议问题