tags:

views:

107

answers:

2

I implemented strstr() myself,the code works fine for all strings but when the string lies in the first index of the string,it returns null.

#include<stdio.h>

const char* mystrstr(const char *str1, const char *str2);

int main()
{
 const char *str1="chal bhai nikal";
 const char *str2="c",*result;
 result=mystrstr(str1,str2);
 if(*result!=NULL)
 printf("found at %d location and the value is %s.",*result, str1+*result);
 else
 printf("Value not found");
 getchar();
 printf("\n");
 return 0;
}

const char * mystrstr(const char *s1, const char *s2)
{
 int i,j,k,len2,count=0;
 char *p;

 for(len2=0;*(s2+len2)!='\0';len2++); //len2 becomes the length of s2
 for(i=0;*(s1+i)!='\0';i++)
 {
  if(*(s1+i)==*s2)
  {
  for(j=i,k=0;*(s2+k)!='\0';j++,k++)
   {
    if(*(s1+j)==*(s2+k))
    count++;
    else count=0;
    if(count==len2)
    {
     p=(char*)malloc(sizeof(char*));
     *p = i;
     return p;
    }
   }
  }
 }
 return NULL;
}
+3  A: 

I haven't looked at your mystrstr function, just main.

const char *str2="c",*result;
result=mystrstr(str1,str2);
if(*result!=NULL)
printf("found at %d location and the value is %s.",*result, str1+*result);
else
printf("Value not found");

result is a const char *; *result is a const char.

Are you perhaps mixing NULL pointer and NUL zero-terminator?

result can be NULL; *result can be '\0'


Edit: possible solution

When strstr() fails to find the substring it returns NULL. Supposing your mystrstr() works the same way, you do

/* result=mystrstr(str1,str2); */
result=NULL;

and then

if(*result!=NULL) {/* ... */} else {}

but *result can try to dereference a NULL pointer, which is NOT what you want.
You want to test result itself

if (result != NULL) { /* ... */ } else {}
pmg
How do I remove the error?Hint?
fahad
@fahad: better description now ... still haven't looked at your mystrstr function
pmg
@pmg:Thanks alot..
fahad
+2  A: 

The problem is that you're returning an index in memory pointed to by a char* (and in this particular case, the matching index is 0, which your code is interpreting as a NULL when it checks the dereferenced result). If you want mystrstr() to have the same behavior as strstr(), you should change:

if(count==len2)
{
 p=(char*)malloc(sizeof(char*));
 *p = i;
 return p;
}

to:

if(count==len2)
{
  return s1+i;
}

so a pointer to the substring location is returned.

strstr() doesn't return an index (or a pointer to an index) - it returns a pointer to the character in the string passed as the first parameter where the instance of str2 is found (if it is found). I assume that your intent is for mystrstr() to follow that specification.

So, you'll also need to change the code that checks and deals with the returned value, but I'll leave that as an exercise for the reader.

Michael Burr
Can you please explain the diffrence between pointer to index and pointer to character as you said?
fahad