Search code examples
cstringsubstringstrchr

C : strchr pointer value doesn't change


I'm trying to recursively search for a substring in a string using C program. I wrote the following piece of code. The issue I'm facing is that, the ptr value, though it prints the correct value(using puts in the beginning of while), while usage its value is not changed! It uses the previous ptr value. I found this out using gdb. I couldn't figure out the cause of this. Kindly guide me to solve this issue. Thanks in advance.

void main()
{
   char buf[10]="hello",*ptr;
   char findc[10]="lo";
   int len,i,lenf,k,l,flag=0;

   lenf=strlen(findc);
   l=0,k=1;
   ptr=strchr(buf,findc[l]);

   while(ptr!=NULL)
   {
      puts(ptr);
      l++;
      for(i=l;i<(lenf);i++,k++)
      {
        if(ptr[k] != findc[i])
        {   
          flag=1;
          break;
        }
      }

      if(flag==1)
      {
        l=0;k=1;
        ptr=strchr((ptr+1),findc[l]);

        if(ptr==NULL)
        {
           puts("String not found");
           break;
        }

      }
      else
      {   
          puts("String found");
        break;
      }
   }
}

Solution

  • It was a very simple mistake!

    We'll have to reset the flag variable in the beginning of the while loop. This would solve the issue.

    Thanks!