char array reversing function using pointer doesnt work..why?

can someone please tell me why does this code doesnt work?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <cstring>
#include <string>

using namespace std;

class my_string
{
    char* ptr;
    int size;
public:
    my_string(){};
    my_string(char* str) : ptr(str),size(strlen(ptr)){};
    char* getstr () {return ptr;};
    void reverse();
    int find (char);
    void print();
};

void my_string::reverse()
{
	for ( int i = 0; i < size/2; i++ )
     {
           char tmp = ptr[i];
           ptr[i] = ptr[size-1-i];
           ptr[size-1-i] = tmp;
     }
     ptr[size] = '\0';
}

int my_string::find(char c)
{
    for (int i=0;i<size;i++)
     {
        if (ptr[i]==c)
        return i;
     }
    return -1;
}

void my_string::print()
{
    for (int i=0;i<size;i++)
        cout<<ptr[i];
    cout<<endl;
}


int main()
{
    my_string s1("abcde");
    s1.print(); 
	s1.reverse();
    s1.print();
}


Define "doesn't work"

The first problem I am seeing is that it attempts to write to a string literal "abcde", which are usually read-only.
Topic archived. No new replies allowed.