-1

I was trying to implement strstr in C but I was stuck at this piece of code which was crashing at runtime

while (*a==*b && a != NULL && b != NULL) {
    a++
    b++
}
if (b == NULL || *b == '\0') { // string found }

After googling for sometime I figured out the mistake https://stuff.mit.edu/afs/sipb/project/tcl80/src/tcl8.0/compat/strstr.c

I should've had my loop do the following:

while (*a==*b && *a != 0 && *b != 0) {
    a++
    b++
}
if (*b === 0) { // string found }

But I'm still not clear on why wouldn't the first approach work as well?

Paul R
  • 208,748
  • 37
  • 389
  • 560

2 Answers2

2

The difference is that a != NULL is not the same as *a != 0.

Recall that a string is an array of characters up to and including the terminating null character '\0'. Rather than pass around strings, code typically passes a pointer to the first character.

a != NULL tests if that pointer is equal to NULL. A pointer with the value NULL is never a string. It is simply a pointer to a location that will never have any valid data.

*a != 0 tests if the pointer a, let us assume it is of type char *, points to a char that does not have the value of of the null character '\0' as that would be the end of the string. Thus the loop should stop.


Note: the loop could be simplified. By the time code reaches *b != 0, it already can not have the value of '\0'.

// while (*a==*b && *a != 0 && *b != 0) {
while (*a==*b && *a != 0) {
    a++
    b++
}
// if (*b === 0) { // string found }  Type use ==, not ===
if (*b == 0) { // string found }
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

You have to deference the pointer to compare it's value.

mreff555
  • 1,049
  • 1
  • 11
  • 21