Pointer Trouble

I am trying to make a substring from a string using a function that returns a pointer. When I try to assign the value pointed by one pointer to another pointer the program just stops executing. It compiles fine however with no errors or anything.

Anyway I am a newbie and was wondering if anybody can see a problem in the code

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
#include<iostream>

char *getSubString(char *str,char *sub);

using namespace std;
int main()
{
    char mystr[]="rainy day women";
    char *sub=getSubString(mystr,"day");
    
    cout<<sub<<endl;
    system("pause");
    return 0;   
}

char *getSubString(char *str,char *sub)
{
     char *ptr;
     while(*str){
     if(*str==*sub)
     {
        cout<<"Match"<<*str<<endl;
        *ptr=*str; //HERE IS WHERE THE PROBLEM IS
        *(sub++);
        *(ptr++);
     }                                  
     *(str++);
     }
     return ptr; 
}
This:
*ptr=*str;
doesn't work, because you didn't allocate memory for pointer ptr. So you should write for example:
char *ptr=new char[20];
Also, you don't have to write:
*(ptr++);
Write:
ptr++;
instead.
Last edited on
Okay thanks alot.
Topic archived. No new replies allowed.