strstr
is a C99-conforming function, the type signature of which is the following:
char *strstr(const char *haystack, const char *needle);
Is it possible to implement this function without casting away a const
somewhere?
For reference, here is Apple's implementation, and here is GNU's implementation. Both cast away the const
at the end.
class Solution { public: int strStr(string haystack, string needle) { if (needle == "") return 0; int i = 0, j = 0, poz = -1; if (needle. size() > haystack. size()) return -1; while (i < haystack. size() && j < needle.
The strstr() function returns a pointer to the beginning of the first occurrence of string2 in string1. If string2 does not appear in string1, the strstr() function returns NULL. If string2 points to a string with zero length, the strstr() function returns string1.
All the const char * is telling you is that strstr is not going to modify the string you pass into it. Whether you modify the returned string or not is up to you as it is your string! In C++ this has been changed by overloading the method and having two versions, the const input version has a const output.
The strstr() function returns pointer to the first occurrence of the matched string in the given string. It is used to return substring from first match till the last character. Syntax: char *strstr(const char *string, const char *match)
You can't implement strstr()
without violating const
correctness somehow. A cast is the most straightforward way to do that. You can probably hide the violation somehow (for example you could use memcpy()
to copy the pointer value), but there's no point in doing so.
The problem is that strstr()
takes a const char*
that points to a string, and returns a non-const
char*
that points into the same string.
For example, this program:
#include <stdio.h>
#include <string.h>
int main(void) {
const char s[] = "hello";
char *result = strstr(s, "hello");
*result = 'H';
puts(result);
}
modifies (or at least attempts to modify) a const
-qualified object, without using a pointer cast or any other obviously unsafe construct.
Back in 1989, the ANSI C committee could have avoided this problem by defining two different functions, say:
const char *strcstr(const char *haystack, const char *needle);
char *strstr ( char *haystack, const char *needle);
one that returns a pointer to a const char
given a const
arguments, and another that returns pointer to a modifiable char
given a modifiable argument. (C++, which inherits the C standard library, does this by overloading.)
strstr()
is one of several standard string functions that have this problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With