Reverse a word with pointers

Hi everyone! I am new on this forum.


I am writing a little program on C++ where I should reverse a word using pointers. I have wrote it but my output is blank. I wish to understand why and what I get wrong.


Here is my code:

int len(const char* s)
{
    int n = 0;
    while (*s != '\0')
    {
        ++n;
        ++s;
    }
    return n;
}
char* reverse_word(char* c)
{
    int n = len(c);
    char* p2 = new char[n + 1];
    char* temp = &p2[n];
  
    while(*c != '\0') *temp-- = *c++;
  
    return p2;
  
}
int main(int argc, const char * argv[])
{
    char ar[] = {"Casa"};
    char* p = &ar[0];
    char* p1 = nullptr;
    p1 =reverse_word(p);
    return 0;
}


Thank you very much!

Answered by OOPer in 41655022

Dump the content of p2 in your reverse_word and you'll see what's happening.

char* reverse_word(char* c)
{
    int n = len(c);
    char* p2 = new char[n + 1];
    char* temp = &p2[n];
  
    while(*c != '\0') *temp-- = *c++;
    //Dump the content of p2
    for(int i = 0; i < n + 1; ++i ) {
        std::cout << (int)p2[i] << std::endl;
    }
  
    return p2;
  
}


(By the way, you should delete[] the memory region allocated with new[] .)

Accepted Answer

Dump the content of p2 in your reverse_word and you'll see what's happening.

char* reverse_word(char* c)
{
    int n = len(c);
    char* p2 = new char[n + 1];
    char* temp = &p2[n];
  
    while(*c != '\0') *temp-- = *c++;
    //Dump the content of p2
    for(int i = 0; i < n + 1; ++i ) {
        std::cout << (int)p2[i] << std::endl;
    }
  
    return p2;
  
}


(By the way, you should delete[] the memory region allocated with new[] .)

Thank you! I have solved the issue and deleted p2's allocated memeory 🙂

Reverse a word with pointers
 
 
Q