Here's another 'reinventing-the-wheel' problem we were given in our Introduction to C++ classes:
Write a function that returns the position of the first occurrence of a sequence of characters in a string, i.e. a variation of the
strstr
function.
I started writing the function as follows:
int strstr2(const char *text, const char *pattern) {
int pos = 0;
char *temp;
temp = text;
}
I thought I'd remember the address of the first character of the string for future use within the function, but the compiler said:
A value of type "const char*" cannot be assigned to an entity of type "char*".
I know that one cannot change a constant once it has been initialized, but why am I not able to assign a pointer to a constant char to another non-constant pointer?
I read several questions referring to pointers and constants, and it seems the bottom of the accepted answer to this post might answer my question, but I'm not a hundred percent sure, as the discussion is still at too advanced a level for me.
My second question is, what is the workaround? How can I define a pointer pointing at the beginning of the string?
Thanks.