一开始的疑问是strstr返回的指针到底指向哪里,所以进行了测试。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<malloc.h>
int main()
{
char *search;
char *str;
char *p;
search = (char*)malloc(strlen("world") + 1);
str = (char*)malloc(strlen("hello world and everyone!") + 1);
memset(search, 0, strlen("world") + 1);
memset(str, 0, strlen("hello world and everyone!") + 1);
strcpy(search, "world");
strcpy(str, "hello world and everyone!");
p = strstr(str, search);
printf("%s\n", p);
free(search);
search = NULL;
free(str);
str = NULL;
return 0;
上面就是测试代码,通过返回值发现返回的时search指针第一次出现的地方。
运行结果:
willing@willing:~/TEST/strstr$ gcc strstr.c -o strstr
willing@willing:~/TEST/strstr$ ./strstr
world and everyone!