[英]My strstr() returning null even if the string to be found is at the index 0
我自己實現了 strstr(),該代碼適用於所有字符串,但當字符串位於字符串的第一個索引時,它返回 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;
}
我沒有看過您的mystrstr
函數,只是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
是一個const char *
; *result
是一個const char
。
您是否可能混合使用NULL pointer
和NUL zero-terminator
?
result
可以為NULL
; *result
可以為'\\0'
編輯:可能的解決方案
當strstr()找不到子字符串時,它將返回NULL。 假設mystrstr()的工作方式相同,
/* result=mystrstr(str1,str2); */
result=NULL;
接着
if(*result!=NULL) {/* ... */} else {}
但是*result
可以嘗試取消引用NULL指針,這不是您想要的。
您要測試result
本身
if (result != NULL) { /* ... */ } else {}
問題是您要返回一個由char*
指向的內存索引(在這種情況下,匹配的索引為0,當您檢查解引用的result
時,您的代碼會將其解釋為NULL)。 如果希望mystrstr()
與strstr()
具有相同的行為,則應更改:
if(count==len2)
{
p=(char*)malloc(sizeof(char*));
*p = i;
return p;
}
至:
if(count==len2)
{
return s1+i;
}
因此將返回指向子字符串位置的指針。
strstr()
不返回索引(或指向索引的指針)-它返回指向字符串中字符的指針,該字符串作為找到str2
實例(如果找到)的第一個參數傳遞。 我假設您的意圖是使mystrstr()
遵循該規范。
因此,您還需要更改檢查和處理返回值的代碼,但我將其留給讀者練習。
上面那位說的還可以。 因為在他的方式中,您不需要聲明指向 char p
的指針並使用malloc
分配 memory 來返回指向 index 的指針。 它可以簡化您的代碼。
但是您需要相應地更改您的main
function。
const char* mystrstr(const char *str1, const char *str2);
int main()
{
const char *str1 = "chal bhai nikal";
const char *str2 = "bh", *result;
result = mystrstr(str1, str2);
if (result != NULL)
{
printf("found at %d location and the value is %s.\n", result - str1, result);
}
else
printf("Value not found");
getchar();
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.