询问者
关于指针的问题?

常规讨论
-
char* str = "smith, where jones had had \"had had \" had had \"had\".""\n\"Had had\" had had the examiners' approval";
char* word = "had";
cout << "The string to be searches is:"
<< str << endl;int count = 0;
char* pstr = str;
char* found = 0;while(true)
{
found = strstr(pstr, word);
if(!found)
break;
count++;
pstr = found+ strlen(word);
}
在这代码中我有一句不懂
pstr = found+ strlen(word);
这句代码是用来改变pstr指针的位置的
但是我不懂为什么用found+ strlen(word);
的值来改变 而且现在的found的值是had \"had had \" had had \"had\".""\n\"Had had\" had had the examiners' approval 这个 而strlen(word)的值是3没错吧? 那加起来是什么?
strstr()函数返回的字符到底是h还是had?怎么我在调试的时候看到的是h ?那么我指定要找had的 那么它是如何识别had的?
法拉利 法拉利 法拉利
全部回复
-
OK
found = strstr(pstr, word);
这句首先在pstr中找第一个"had"出现的位置。返回指向这个位置的指针。那么在第一次循环的时候
found将指向"had had \"had had \" had had \"had\".""\n\"Had had\" had had the examiners' approval"
也就是说found是指向一个字符串的指针,而不是一个字符。只能看到h是调试只看到了指针指向的第一个字符而已。但实际上found指向了一个字串。
strlen(word)这个返回3个字符长度。
pstr = found+ strlen(word);
是指针偏移操作。使得
pstr在下一次循环过程中指向had \"had had \" had had \"had\".""\n\"Had had\" had had the examiners' approval"。去掉了found字串头的had。
这样循环
最后pstr会变成"the examiners' approval"。而此时字串中没有"had",结束循环。
麻烦把正确答案设为解答。 -
OK
found = strstr(pstr, word);
这句首先在pstr中找第一个"had"出现的位置。返回指向这个位置的指针。那么在第一次循环的时候
found将指向"had had \"had had \" had had \"had\".""\n\"Had had\" had had the examiners' approval"
也就是说found是指向一个字符串的指针,而不是一个字符。只能看到h是调试只看到了指针指向的第一个字符而已。但实际上found指向了一个字串。
strlen(word)这个返回3个字符长度。
pstr = found+ strlen(word);
是指针偏移操作。使得
pstr在下一次循环过程中指向had \"had had \" had had \"had\".""\n\"Had had\" had had the examiners' approval"。去掉了found字串头的had。
这样循环
最后pstr会变成"the examiners' approval"。而此时字串中没有"had",结束循环。
麻烦把正确答案设为解答。
哦 有点理解了!!但是你说strlen(word)这个返回3个字符长度。
pstr = found+ strlen(word);是指针偏移操作
我不懂为什么要相加 你说是指针偏移操作 它是一样怎样的偏移过程?
不好意思啊 不知道为什么这个主题不能设置标记为答案 不知道咋搞的
法拉利 法拉利 法拉利