char*newx=p+strlen(str1);这将如何执行,因为strstr将返回指向另一个字符串的第一个匹配字符的
char *newx=p+strlen(str1); how this will execute because strstr will return the pointer to the first match character of the another string
我不明白这段代码将如何执行。据我所知,strstr()将返回一个指向匹配字符串的第一个字母的指针。那么,当p
是指针并且strlen()返回整数值时,我们如何执行char *newx=p+strlen(str1);
呢?
p=strstr(str2,str1);
if(p){
char *newx=p+strlen(str1);
strcpy(t,newx);
}
这是一个简单的指针算术。
向指针添加整数会使指针增加指定数量的元素。
假设您有一个指针T *ptr
。当你做这样的事情时:
T *ptr2 = ptr + N;
编译器实际上做了(优化的)等效的事情:
T *ptr2 = reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(ptr) + (sizeof(T) * N));
因此,有问题的代码使用strstr()
在str2
字符串中搜索子字符串str1
,并获得指向该子字符串的指针。如果找到子字符串,则指针通过strlen()
递增到子字符串末尾后的字符的地址,然后strcpy()
用于将该地址的剩余文本复制到t
字符串中。
例如:
const char *str2 = "Hello StackOverflow";
const char *str1 = "Stack";
const char *p;
char t[10];
p = strstr(str2, str1); // p points to str2[6]...
if (p) { // substring found?
const char *newx = p + strlen(str1); // newx points to str2[11]...
strcpy(t, newx); // copies "Overflow"
}
这是一个关于指针算术的问题。我建议你阅读https://www.tutorialspoint.com/cplusplus/cpp_pointer_arithmatic.htm有关指针算术的更多信息。
对于这个问题,需要说明的是,当您将str1
的大小添加到newx
时,它会自动识别您正在增加一个字符指针,因此地址需要增加sizeof(char) * strlen(str1)
希望这能澄清你的问题,并强烈建议你通读指针算术。
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- QueryWorkingSet总是返回false
- (C++)分析树以计算返回错误值的简单算术表达式
- 访问者访问变体并返回不同类型时出错
- 如何返回一个类的两个对象相加的结果
- OpenInventor从9.8升级到10.4.2后,GLSL纹理返回零
- lower_bound()返回最后一个元素
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 如何取消对nullptr的屏蔽,返回正确的对象
- 奇怪的结构&GCC&clang(void*返回类型)
- 架构决策:返回std::future还是提供回调
- char*newx=p+strlen(str1);这将如何执行,因为strstr将返回指向另一个字符串的第一个匹配字符的
- strstr 返回如何不是一个常数
- leetcode实现strstr c++返回指针