I've got this simple strstr
re-making as an exercise but there's an error I don't understand
#include <iostream>
#include "windows.h"
using namespace std;
int strstr2(char *arr, char *findme)
{
const int sizearr = sizeof(arr) / sizeof(char);
const int sizefindme = sizeof(findme) / sizeof(char);
int j=0;
for(int i=0; i<sizearr; i++)
{
if(arr[i] == findme[j])
{
// Match
if(j == sizefindme-1)
return i;
else
j++;
}
else
{
j = 0;
}
}
return -1;
}
int main (int argc, char **argv)
{
char arr[] = "I'd like 2% milk";
char toBeFound[] = "like";
int pos = strstr2(arr, toBeFound);
Sleep(3000);
}
For some reason the line
const int sizefindme = sizeof(findme) / sizeof(char);
returns sizefindme = 8
while the length of the string "like"
is actually 4 (or 5 with the null terminator). And the null terminator is actually present in the toBeFound
array. What's wrong with sizeof
? I can't spot the error.