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


将长度为21个字节的字符数组传递给函数。
遍历链表的节点,将每个节点的字符数组与第1点中提到的通过的数组进行比较
strstr始终返回NULL,而不管传递的任何字符串如何
举例来说,像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/

10-13 02:22