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 str1 newx 执行      更新时间:2023-10-16

我不明白这段代码将如何执行。据我所知,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)

希望这能澄清你的问题,并强烈建议你通读指针算术。