sách gpt4 ăn đã đi

c++ - 指针算术递增后缀/前缀

In lại 作者:搜寻专家 更新时间:2023-10-31 00:08:46 27 4
mua khóa gpt4 giày nike

我无法理解下面一段特定代码的逻辑。

int i[] = { 21, 4, -17, 45 };

int* i_ptr = i;

std::cout << (*i_ptr)++ << std::endl; // 21

std::cout << *i_ptr << std::endl; // 22

std::cout << *i_ptr++ << std::endl; // 22

std::cout << *(i_ptr - 1) << std::endl; // 22

std::cout << *i_ptr << std::endl; // 4

std::cout << ++*i_ptr << std::endl; // 5

std::cout << *++i_ptr << std::endl; // -17

system("pause");

我的问题是这段代码是如何从 22...开始的

std::cout << *(i_ptr - 1) << std::endl; // 22

到 4。

std::cout << *i_ptr << std::endl; // 4

然后到 5.

std::cout << ++*i_ptr << std::endl; // 5

当我第一次浏览这段代码时,我以为 22 只是从 22 到 21。我知道它与 C++ 运算符优先级有关,但这对我来说毫无意义。

câu trả lời hay nhất

std::cout << (*i_ptr)++ << std::endl; // 21
//i_ptr points to i[0], which is increased from 21 to 22

std::cout << *i_ptr << std::endl; // 22
//prints i[0], which is 22

std::cout << *i_ptr++ << std::endl; // 22
//prints i[0] and increments i_ptr to point to i[1]

std::cout << *(i_ptr - 1) << std::endl; // 22
//prints i[0], i_ptr points to i[1], so i_ptr - 1 points to i[0]

std::cout << *i_ptr << std::endl; // 4
//prints i[1], which is 4

std::cout << ++*i_ptr << std::endl; // 5
//prints the incremented i[1], which was 4 and is 5 now

std::cout << *++i_ptr << std::endl; // -17
//increment i_ptr to point to i[2] and prints the value

关于c++ - 指针算术递增后缀/前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47081085/

27 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress