初始化“指向整数数组的指针" [英] Initializing "a pointer to an array of integers"

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

问题描述

 int (*a)[5];

我们如何初始化一个指向上面显示的 5 个整数数组的指针.

How can we Initialize a pointer to an array of 5 integers shown above.

下面的表达是否正确?

int (*a)[3]={11,2,3,5,6}; 

推荐答案

假设你有一个长度为 5 的 int 数组,例如

Suppose you have an array of int of length 5 e.g.

int x[5];

然后你可以做 a = &x;

 int x[5] = {1};
 int (*a)[5] = &x;

访问数组元素:(*a)[i] (== (*(&x))[i]== (*&x)[i] == x[i]) 需要括号,因为 [] 运算符的优先级高于 *.(一个常见的错误可能是使用 *a[i] 来访问数组的元素).

To access elements of array you: (*a)[i] (== (*(&x))[i]== (*&x)[i] == x[i]) parenthesis needed because precedence of [] operator is higher then *. (one common mistake can be doing *a[i] to access elements of array).

明白你问的是编译时错误:

Understand what you asked in question is an compilation time error:

int (*a)[3] = {11, 2, 3, 5, 6}; 

它不正确,也是类型不匹配,因为 {11,2,3,5,6} 可以分配给 int a[5]; 和您正在分配给 int (*a)[3].

It is not correct and a type mismatch too, because {11,2,3,5,6} can be assigned to int a[5]; and you are assigning to int (*a)[3].

另外,

你可以对一维做类似的事情:

You can do something like for one dimensional:

int *why = (int p[2]) {1,2};

同样,对于二维试试这个(感谢@caf):

Similarly, for two dimensional try this(thanks @caf):

int (*a)[5] = (int p[][5]){ { 1, 2, 3, 4, 5 } , { 6, 7, 8, 9, 10 } };

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

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