Hello everyone,

I'm trying to write a recursive function that receives a string and checks whether all characters are capital or not, if not changes them into capital. Here is the code I wrote:

#include <iostream>
  2 using namespace std;
  3 
  4 void toUpperString(char *p);
  5 
  6 int main()
  7 {
  8         char str[] = "my name is sam";
  9         
 10         char *p;
 11         
 12         p = str;
 13         
 14         toUpperString(str);
 15         
 16         for (; *p != '\0'; p++)
 17         {
 18                 cout << *p;
 19         }       
 20         
 21         cout << endl;
 22         
 23 
 24 }
 25 
 26 
 27 void toUpperString(char *p)
 28 {
 29         if (*p == '\0')
 30                 return;
 31         else    
 32         {
 33                 int asc = *p;
 34                 if(asc > 96)
 35                         asc -= 32;
 36                         
 37                 *p = char(asc);
 38                 
 39                 cout << *p << endl;
 40                          
 41                 toUpperString(p++);
 42         }       
 43 }

there is no compilation error, but when I try to run the program, it says:

Segmentation Fault (I'm using ubuntu).

Please let me know where I'm going wrong.

Thanks a lot.

OHHHH MYYYY GOOODDDD!

it worked. you have no idea how much time I spent on it. And could you please tell me what is wrong with p++???

Use a debugger, step through the code with both forms, and observe carefully the value of the pointer passed in the recursive call, and the value received in the next invocation of the call.

You've used the post increment operator(p++) to increment the pointer which increments after the operation. Therefore p captures the same address for every recursion. Try using a ++p it should work.

Yeah, I thought of ++p as well, but I didn't try it. Anyhow, thank you so much guys, it's so sweet to learn.

This article has been dead for over six months. Start a new discussion instead.