gpt4 book ai didi

c - 使用 strstr 函数时出现问题

转载 作者:行者123 更新时间:2023-11-30 20:28:27 26 4
gpt4 key购买 nike

我在使用 strstr 时遇到问题。这是我所拥有的:

  1. 将长度为 21 字节的字符数组传递给函数。

  2. 遍历链表的节点,将每个节点的字符数组与上面第 1 点中提到的传递的数组进行比较

  3. strstr 始终返回 NULL,无论传递任何字符串

  4. 比方说像 strstr("hello","he") 这样的代码。它应该返回指向“hello”的指针,但这在我下面的代码中永远不会发生。它总是返回NULL

以下是该程序的代码片段:

 void display_to_file(const char *chr,c_uint32 pos_in_list,c_uint32 line_no)
{
NODE *search = ptrs_to_heads_of_alpha[pos_in_list];
char *chk;
char redundant[21]={'\0'};
int first=1;
uint32 count = 0;

while((NULL!=search) && (count<21))
{
printf("\nsearch->arg=%s",search->arg); /*for example search->arg is "hello"*/
/*above statement prints "hello"-correctly*/
/*for example chr="?he" */
printf("\nchr=%s",&chr[1]); /*prints "he" correctly*/
chk=strstr(search->arg,&chr[1]);
if(chk != NULL) /*is always null- not known why it returns null even for valid cases*/
{
printf("\nentered_\n");
++count;
if(1 == first)
{
fprintf(op_fp," %s\n",search->arg);
strcpy(redundant,search->arg);
printf("\nop:%s\n",search->arg);
first = 0; /*only for first node print*/
}
else
{
if(strcmp(redundant,search->arg) == 0)/*duplicate found*/
--count; /*need to search for one more item*/
else
{
fprintf(op_fp," %s\n",search->arg);
strcpy(redundant,search->arg);
}
}
}
else
printf("\nelse,else,else\n\n"); /*Always this statement is executed even
if I passed valid arguments*/

search=search->next;
}
}

最佳答案

此语句在编译时是否有任何警告?:

   chk=strstr(search->arg,&chr[1]); 

第二个参数应该是 strstr() 中的 const char *确保这件事。

使用此语句还可以尝试一件事

 chk=strstr(search->arg,"he"); 

还要检查一下您是否已包含 string.h

  #include<string.h>

关于c - 使用 strstr 函数时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6995600/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com