0
#include <stdio.h>
#include <string.h>

int main()
{
    char s3[12]="ABCDEISHERO";    
    char s4[5]="ABCDE";
    char* p=strstr(s3,s4);
    printf("%s",p);

    return 0;
}

I wrote this code, but according to the functionality of strstr, we have substring "ABCDE" in string s3, but why is the output (null)? Where am I going wrong?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Heatblast
  • 55
  • 6
  • 7
    Tip: Don't declare strings with fixed lengths like this. Use `char s[] = "..."` and let the compiler figure it out for you. You've guessed the lengths wrong here. If you don't need a mutable character buffer, just use `char* s = "..."` instead. – tadman May 13 '21 at 19:13
  • 3
    Your arrays sizes do not account for null-terminator. – SergeyA May 13 '21 at 19:13
  • 2
    `s4` needs to be 6 elements wide to account for the string terminator - `strstr` isn't matching it because (most likely) there are one or more non-zero bytes following the last character, so `strstr` sees `s4` as `"ABCDEandabunchofothercharacters"`, not `"ABCDE"`. – John Bode May 13 '21 at 19:15
  • 1
    @tadman No, use `const char *s = "..."`. – August Karlstrom May 13 '21 at 19:24
  • @AugustKarlstrom Ideally, yes. – tadman May 13 '21 at 19:31

2 Answers2

1

s4 needs to be 6 elements wide to account for the string terminator - strstr isn't matching it because (most likely) there are one or more non-zero bytes following the last character, so strstr sees s4 as "ABCDE???????", not "ABCDE".

Answered by John Bode.

anatolyg
  • 26,506
  • 9
  • 60
  • 134
1

This declaration

char s4[5]="ABCDE";

is valid in C but is not valid in C++.

The problem with this declaration is that the array s4 does not contain a string. In C "a string" means "a null-terminated sequence of bytes", and s4 does not have a space to accommodate the terminating zero character '\0' of the string literal "ABCDE" used as an initializer.

Thus calling the function strstr that expects that the both arguments will be pointers to strings results in undefined behavior.

Either write

char s4[6]="ABCDE";

or even better

char s4[]="ABCDE";

Here is a demonstrative program

#include <stdio.h>
#include <string.h>

int main(void) 
{
    char s3[12] = "ABCDEISHERO";    
    char s4[] = "ABCDE";

    char* p = strstr( s3, s4 );

    if ( p ) printf( "%s\n", p );
    
    return 0;
}

The program output is

ABCDEISHERO

because the returned by the call of the function strstr pointer p points to the beginning of the character array s3.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335