I relatively new to low level programming such as c. I am reviewing the strstr() function here. When reviewing the function definition char *strstr(const char *str1, const char *str2);
I understand that function will return a pointer or a NULL depending if str2 was found in str1.
What I can't understand though, is if the funciton requires the two inputs to be pointers, when does the example not use pointers?
#include <string.h>
int main ()
{
char string[55] ="This is a test string for testing";
char *p;
p = strstr (string,"test");
if(p)
{
printf("string found\n" );
printf ("First occurrence of string \"test\" in \"%s\" is"\
" \"%s\"",string, p);
}
else printf("string not found\n" );
return 0;
}
In strstr(string,"test");
, string
is an array of 55 char
. What strstr
needs here is a pointer to the first element of string
, which we can write as &string[0]
. However, as a convenience, C automatically converts string
to a pointer to its first element. So the desired value is passed to strstr
, and it is a pointer.
This automatic conversion happens whenever an array is used in an expression and is not the operand of sizeof
, is not the operand of unary &
, and is not a string literal used to initialize an array.
"test"
is a string literal. It causes the creation of an array of char
initialized with the characters in the string, followed by a terminating null character. The string literal in source code represents that array. Since it is an array used in an expression, it too is converted to a pointer to its first element. So, again, the desired pointer is passed to strstr
.
You could instead write &"test"[0]
, but that would confuse people who are not used to it.