Pointer Wont Print out to Console

Hi I am trying to make a program that returns a substring of a string if it is found. The cout statement works but the pointer variable inside it prints no contents. I have ran the program with a debugger and the pointer variable definetely has contents.

Can anybody see why it wont print to the console:

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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

#include<iostream>
#include<limits>

using namespace std;

void pause()
{
 cin.clear();
 cout<<"Press Enter to Quit: ";
 cin.ignore(numeric_limits<streamsize>::max(),'\n');     
}

char *createSubString(char *str,char *sub,int len);

int main()
{
 char mystr[80];
 char *sub;
 char mystr2[80]; 
 int len;
 
 cout<<"Enter a String: ";
 gets(mystr);
 len=strlen(mystr);
 
 cout<<"Enter a substring to search: ";
 gets(mystr2);
 
 sub=createSubString(mystr,mystr2,len);
 
 if(sub){
   cout<<"Substring Found: "<<sub<<endl; //SUB DOES NOT PRINT OUT
 }
 else{
   cout<<"Substring not Found!"<<endl;   
 }
 pause();   
 return 0;   
}

char *createSubString(char *str,char *sub,int len)
{
     char *start;
     char *ptr;
     char *ptr2;
     int count=0;
     
     while(count<len)
     {
      start=&str[count];           
      ptr2=start;
      ptr=sub;
      
      while(*ptr==*ptr2 && *ptr)
      {
        ptr2++;
        ptr++;                             
      }
      
      //if end of *ptr then above while loop must have found match
      //so return the match
      if(!*ptr)
      {
        cout<<ptr<<endl;       
        return ptr;       
      }
        
      count++;                 
     }
     //return 0 if no substring found
     return 0;
}


Any help much appreciated
Thanks for the links. I am doing this exercise just to learn pointers.

Its okay anyhow I just figured out why it was happening. ptr was getting incremented inside the while loop so by the time I returned it it was not the full substring. I had to do this before I returned it.


1
2
3
4
5
 if(!*ptr)
      { 
        ptr=sub;             
        return ptr;       
      }
Topic archived. No new replies allowed.