gpt4 book ai didi

c++ - 为什么 strstr() - char pointer = number?

转载 作者:太空狗 更新时间:2023-10-29 23:48:59 26 4
gpt4 key购买 nike

我有这个程序:

#include <iostream>
#include <conio.h>
#include <string.h>

using namespace std;

int main()
{
char char1[30] = "ExtraCharacter", char2[30] = "Character", *p;

p = strstr(char1, char2);
cout << "p: " << p << endl;
cout << "char1: " << char1 << endl;
cout << "(p-char1): " << (p-char1) << endl;

return 0;
}

当我运行它时,我得到:

p: Character
char1: ExtraCharacter
(p-char1): 5

正如预期的那样。

但这不是问题,我不确定为什么"Character" - "ExtraCharacter"是一个整数(5)?也许不是整数,而是数字/数字。其实我不明白为什么“字符”存储在p中,而不是内存地址。

如果我从书上理解的很好,strstr()返回一个内存地址,它不应该更像是一个奇怪的值,比如十六进制 (0x0045fe00) 或类似的东西吗?我的意思是,它是 cout << p不是 cout << *p显示该内存地址的实际值。

谁能给我解释一下它是如何工作的?

P.S.:如果标题不是那么连贯,我深表歉意。

最佳答案

But this is not the problem, I'm not sure why "Character" - "ExtraCharacter" is an integer (5)?

你从一个指针中减去另一个指针,结果 - 数字,从 char char1 指向 char p 的距离> 指向。这就是指针算法的工作原理。

注意:只有当两个指针都指向同一个数组(或最后一个元素之后)时,此减法才有效,您的代码就是这种情况,但您需要小心。例如,如果 strstr() 没有找到 susbtring,那么它将返回 nullptr 并且您的减法将有 UB。所以至少在减去之前检查 p(并将 nullptr 传递给 std::cout 也会有 UB)

If I understood well from a book, strstr() returns a memory address, shouldn't it be more like a strange value, like a hex (0x0045fe00) or something like that? I mean, it's cout << p not cout << *p to display the actual value of that memory address.

是的 p 是一个指针,也就是内存地址。 std::ostream 有特殊规则如何将指向 char 的指针打印为字符串,因为 C 中的字符串以这种方式存储。如果您想将其视为指针,只需将其转换为:

std::cout << static_cast<void *>( p );

然后你会看到它是一个地址。

关于c++ - 为什么 strstr() - char pointer = number?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48688685/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com