C语言 初始化“指向整数数组的指针”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17850998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:00:40  来源:igfitidea点击:

Initializing "a pointer to an array of integers"

carrayspointersinitialization

提问by EnterKEY

 int (*a)[5];

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

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

Is the below expression correct ?

下面的表达正确吗?

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

回答by Grijesh Chauhan

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

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

int x[5];

Then you can do a = &x;

然后你可以做 a = &x;

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

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).

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

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

了解您所问的是编译时错误:

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

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].

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

Additionally,

此外,

You can do something like for one dimensional:

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

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

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

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

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

回答by Lundin

{11,2,3,5,6}is an initializer list, it is not an array, so you can't point at it. An array pointer needs to point at an array, that has a valid memory location. If the array is a named variable or just a chunk of allocated memory doesn't matter.

{11,2,3,5,6}是一个初始化列表,它不是一个数组,所以你不能指向它。数组指针需要指向具有有效内存位置的数组。如果数组是一个命名变量或者只是一块分配的内存并不重要。

It all boils down to the type of array you need. There are various ways to declare arrays in C, depending on purpose:

这一切都归结为您需要的数组类型。有多种方法可以在 C 中声明数组,具体取决于目的:

// plain array, fixed size, can be allocated in any scope
int array[5] = {11,2,3,5,6};
int (*a)[5] = &array;

// compound literal, fixed size, can be allocated in any scope
int (*b)[5] = &(int[5]){11,2,3,5,6};

// dynamically allocated array, variable size possible
int (*c)[n] = malloc( sizeof(int[n]) );

// variable-length array, variable size
int n = 5;
int vla[n];
memcpy( vla, something, sizeof(int[n]) ); // always initialized in run-time
int (*d)[n] = &vla;

回答by Lundin

int a1[5] = {1, 2, 3, 4, 5};
int (*a)[5] = &a1;

回答by Stefano Falasca

int vals[] = {1, 2};
int (*arr)[sizeof(vals)/sizeof(vals[0])] = &vals;

and then you access the content of the array as in:

然后您访问数组的内容,如下所示:

(*arr)[0] = ...