1

I'm trying to brush up on my C/C++ and I seem to have forgotten how to properly manipulate char arrays.

Code:

#include <iostream>
#include <string.h>

void reverse(char* str)
{
    int numChar = strlen(str);
    char *reversed = (char*)malloc(sizeof(char) * (numChar + 1));

    int i = numChar;
    int j = 0;
    while(i >= 0)
    {
        reversed[j] = str[i];
        j++;
        i--;
        printf("%c", reversed[j]);
    }

    printf("%s", reversed);
}

int main()
{
    char* str;
    strcpy(str, "apple\0");
    reverse(str);
    return 0;   
}

I'm very certain I'm not doing what I intend to with reversed[j] = str[i] as reversed comes out empty. What's the correct way to go about this?

2 Answers 2

4

From first glance, In main(), memory has to be allocated to character pointer str before referencing it in strcpy

int main()
{
    char* str = malloc(6)  or use char str[6];
    // or char *str = "apple"; is sufficient, strcpy is not required in this case 
    strcpy(str, "apple\0");
    reverse(str);
    return 0;   
}

Another one : In reverse() function, you will have to increment j after printing

while(i >= 0)
{
    reversed[j] = str[i];
    printf("%c", reversed[j]);
    j++;         //Moved here
    i--;
}
reversed[j] = '\0'          //Null termination

printf("\n %s", reversed);

or only the below two statements would be sufficient enough to post increment j and decrement i

reversed[j] = str[i--];
printf("%c", reversed[j++]);
Sign up to request clarification or add additional context in comments.

Comments

3

Since you start with i being the strlen of the input string (e.g. HAHA -> 4), you start copying at haha[4], which is the null byte at the end of the string. IOW you just null terminated your output right at the start. Try setting i to numChar - 1.

(After fixing the problem Santosh A mentioned)

And then, make sure you null terminate the result!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.