指向整数数组的指针 [英] Pointer to an array of ints

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

问题描述

两者之间有什么区别

//Example of "Complicated Array Declarations" from C++ Primer
int arr[10] = {1,2,3,4,5,6,7,8,9,10};
int (*Parr)[10] = &arr;

并且:

int arr[10] = {1,2,3,4,5,6,7,8,9,10};
int *Parr = arr;

都是指向整数数组的指针.但是为了访问第一个代码段中的arr的第一个元素,我必须执行**Parr,而在第二个代码段中,我只需要取消引用一次*Parr

Both are pointers to an array of integers. But in order to access the first element of arr in the first snippet, I have to do **Parr whereas in the second, I only have to dereference once *Parr

推荐答案

在第一个代码示例中,

int (*Parr)[10] = &arr;

Parr是指向10个整数的数组的指针.它只能指向这样的对象.例如,

Parr is a pointer to an array of 10 ints. It can only point to such an object. For example,

int (*Parr)[10];
int a[10];
Parr = &a; // OK
int b[42];
Parr = &b; // ERROR, b is of the wrong type

在第二个代码示例中,

int *Parr = arr;

Parr是指向int的指针,已初始化为指向arr的第一个元素.但是它可以指向任何int.

Parr is a pointer to int, initialized to point to the first element of arr. But it can point to any int.

int* Parr;
int a[10];
Parr = &a; // OK, a decays to int*
int b[42];
Parr = &b; // OK, b decays to int*
int c = 42;
Parr = &c; // OK, c is an int*

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

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