任何人都可以解释一下这个C ++指针代码的输出吗? [英] Can anyone please explain me the output of this C++ pointer code?

查看:64
本文介绍了任何人都可以解释一下这个C ++指针代码的输出吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
using namespace std;
int main()
{
 int* a = new int[10];
 for(int i = 0; i<10; i++)
 a[i] = i;
 int* b = &a[2];
 cout << b[3];
}




Output: 5





我尝试了什么:



我不明白为什么输出为5.



What I have tried:

I don't understand why the output is 5.

推荐答案

输出的原因是指针算术。数组按顺序存储在内存中。因此,从一个值到下一个值的偏移量是类型的大小。整数= 4个字节,float = 4个字节,double = 8个字节等。这是指针算法工作的根本原因。当你说[2]时,你真正要说的是指向数组开头的指针(即第一个元素)加上两个偏移值的整数来达到第三个值。您可以通过执行*(a + 2)来测试它,这将产生与[2]相同的结果。



那么您发布的代码中发生了什么:a [2]的地址(&)被分配给b。然后,您将打印到标准输出流的值为3个偏移值的整数(b [3])。这是5.



b [0] = a [2]

b [1] = a [3]

b [2] = a [4]

b [3] = a [5]
The reason for that output is something called pointer arithmetic. Arrays are stored sequentially in memory. So the offset from one value to the next is the size of the type. Integer = 4 bytes, float = 4 bytes, double = 8 bytes, etc. This is the fundamental reason why pointer arithmetic works. When you say a[2], what you're really saying is "the pointer to the start of the array (i.e. the first element) plus two offsets worth of integers to reach the third value." You can test this by doing "*(a+2)" which will yield the same result as a[2].

So what's happening in the code you posted: the address (&) of a[2] is being assigned to b. Then you're printing to the standard output stream the value of 3 offsets worth of integers (b[3]). This is 5.

b[0] = a[2]
b[1] = a[3]
b[2] = a[4]
b[3] = a[5]


这篇关于任何人都可以解释一下这个C ++指针代码的输出吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆