String reverse pointer issue

Could anyone please tell me what wrong I am doing here with a simple string reverse function


#include<iostream.h>

void strreva(char *);

int main()
{
char *source;
source = (char *)malloc(sizeof(char)*20);
cout << " Enter the source string: " << endl;
cin >> source;
strreva(source);
return 0;
}

void strreva(char *s)
{
int i=0,n=0,count;
char *dest=NULL;

while(s[n]!='\0') // To get string length
n++;

while(i!=n-1)
{
*dest=*s; // <-- Is there something wrong with this?
dest++;
s--;
i++;

}
cout << "Reverse is " << dest << endl;
}

Thanks,
Steve.
Yes, because dest doesn't point to anything. You cannot dereference it without generating a memory access fault.
You haven't allocated any memory for dest. Here's a rewrite of strreva():
1
2
3
4
5
6
7
8
9
void strreva(char *s)
{
    char dest[20];
    char* d = dest + strlen( s ); // Start d pointer pointing to end of dest.
    *d-- = 0; // zero terminate it
    while( *s )  // while we haven't hit the null char
        *d-- = *s++;
    std::cout << "Reverse is " << dest << '\n';
}


Also, in C++ you usually use new (not malloc).
Thank you Duoas and Hammurabi !!!
Topic archived. No new replies allowed.