使用指针访问数组的值 [英] Accessing value of array using pointers

查看:104
本文介绍了使用指针访问数组的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道我们可以使用指针动态创建变量,例如:

We know that we can dynamically create variables using pointers as for example:

int *p = new int(5);

我们可以使用 * as

cout << *p;

但这不是数组的情况,请考虑以下代码:

But this is not the case of the array, consider the below code:

int size_array = 5;
int * p = new int[size_array];

如果需要访问第一个元素的值,请执行以下操作:

if we need to access the value of the first element, we do the following:

cout << p[0];

但是为什么我们不能像上面那样对动态变量执行相同的操作?即使用 * :

but why we can't do the same as for a dynamic variable like above?, i.e. using *:

cout << *p[0];

推荐答案

p [0] 是以下语法的糖(用于数组):

p[0] is syntax sugar (for arrays) for:

*(p + 0)

等同于:

*p


* p [0] 无效,因为它等效于:

**p

换句话说,两次取消对指针/数组的引用.

In other words, de-referencing the pointer/array twice.

这篇关于使用指针访问数组的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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