gpt4 book ai didi

c++ - 指针可以用于访问内存中的任意区域吗?

转载 作者:行者123 更新时间:2023-11-30 03:13:49 25 4
gpt4 key购买 nike

我对 C++ 和指针非常陌生。

#include <iostream>

using namespace std;

int main() {
char* c = "my name jeff";
int i = 0;
while (true) {
cout << *(c + i++);
}
return 0;
}

输出是“my name jeff”,后跟许多随机字符,偶尔有意义。我实际上是在访问计算机中的内存吗?为什么可以从字符串初始化指针?

最佳答案

来自 https://eel.is/c++draft/expr#add-4

When an expression J that has integral type is added to or subtracted from an expression P of pointer type, the result has the type of P.

(4.1) If P evaluates to a null pointer value and J evaluates to 0, the result is a null pointer value.

(4.2) Otherwise, if P points to an array element i of an array object x with n elements ([dcl.array]),77 the expressions P + J and J + P (where J has the value j) point to the (possibly-hypothetical) array element i + j of x if 0 ≤ i + j ≤ n and the expression P - J points to the (possibly-hypothetical) array element i − j of x if 0 ≤ i − j ≤ n .

(4.3) Otherwise, the behavior is undefined.

因此,使用 "my name jeff"(属于 const char[13] 类型(带有额外的 '\0' )),一旦你执行了 c[14],你就有了 UB。

关于c++ - 指针可以用于访问内存中的任意区域吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58417396/

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