指向数组 C++ 的指针 [英] pointer to array c++
本文介绍了指向数组 C++ 的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面的代码在做什么?
int g[] = {9,8};
int (*j) = g;
根据我的理解,它创建了一个指向 2 个整数数组的指针.但是为什么这样做会起作用:
From my understanding its creating a pointer to an array of 2 ints. But then why does this work:
int x = j[0];
这不起作用:
int x = (*j)[0];
推荐答案
括号在您的示例中是多余的.指针不关心是否涉及数组 - 它只知道它指向一个 int
The parenthesis are superfluous in your example. The pointer doesn't care whether there's an array involved - it only knows that its pointing to an int
int g[] = {9,8};
int (*j) = g;
也可以改写为
int g[] = {9,8};
int *j = g;
也可以改写为
int g[] = {9,8};
int *j = &g[0];
指向数组的指针看起来像
a pointer-to-an-array would look like
int g[] = {9,8};
int (*j)[2] = &g;
//Dereference 'j' and access array element zero
int n = (*j)[0];
在此链接中对指针声明(以及如何理解它们)有很好的阅读:http://www.codeproject.com/Articles/7042/How-to-interpret-complex-CC-declarations
There's a good read on pointer declarations (and how to grok them) at this link here: http://www.codeproject.com/Articles/7042/How-to-interpret-complex-C-C-declarations
这篇关于指向数组 C++ 的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文