数组int* ptr[10]的指针是什么,它是如何工作的?

问题描述

<div idtag=11111 analitycstag=2222>
      [varnish cache hit content]
</div>

我期望int (*ptr)[10]; ptr整数的指针数组。

我不明白它是如何指向10整数数组的指针。

解决方法

ptr的类型为“指向10个整数的数组的指针”。在您的声明中,它是未初始化的,因此它没有指向任何对象。使其指向数组:

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

// initialize in the declaration:
int (*ptr) [10] = &arr;

// or after:
int (*ptr) [10];
ptr = &arr;
,

指向10个int数组的指针的目的是指向10个元素的数组,不多也不少,或者如果您具有2D数组,则指向该数组的给定行,前提是该列正好有10列。

指向intint *ptr[10]的指针数组就是这样,它有10个指向int的指针,指向每个指针,您可以分配一个int的地址。 ,它是否可以是数组的一部分。

示例1:

int (*ptr)[10];

int arr[10];
ptr = &arr; //correct,arr has 10 elements

int arr2[12]; 
ptr = &arr2; //not correct,arr2 does not have 10 elements

此类指针可用于指向行数不确定但列数固定的2D数组。

示例2:

int arr[5][10];
ptr = arr; //correct,pointer to the 1st row of a 2D array with 10 cols
ptr++; //now points to the second row        
    
int arr2[5][12]; 
ptr = arr2; //not correct,incompatible pointer,has too many cols

示例3:

int(*ptr)[3];

int arr[2][3] = {{1,3},{4,7}};
ptr = arr;

printf("%d",ptr[1][2]); //array indexing is identical as using arr[1][2] 

指针数组与指向数组的指针

当需要动态分配/释放内存时,指向数组的指针的一个优点是:

具有4行5列的2D数组的示例:

int (*ptr)[5]; 
ptr = calloc(5,sizeof *ptr); //simple assignment

free(ptr); //simple deallocation
int *ptr[5];

for (int i = 0; i < 5; i++)  //each pointer needs it's own allocation
    ptr[i] = calloc(5,sizeof **ptr);

for (int i = 0; i < 5; i++)  //each pointer needs to be freed
    free(ptr[i]);

另一方面,如果您有一个指针数组,则可以有一个 uneven 数组,也就是说,第一行可以有10个int,而第二行可以有20:

int *ptr[5];

for (int i = 0; i < 5; i++)
    ptr[i] = calloc( i + 1,sizeof **ptr);

在上面的示例中,二维数组的第一行的空间为1 int,第二行的空间为2,第三行的空间为3,依此类推。

,

我喜欢这样阅读:(已经发布了很好的答案)

int (*ptr) [10];
     ^ a pointer
           ^ to an array of 10
^ ints

vs

int* ptr[10];
        ^ array of 10
   ^ pointer to int
,

声明给出了变量使用方式的“图片”。 1 .d.ts表示“在表达式中使用int (*ptr) [10]时,它是{{ 1}}。”由此,我们可以得出(*ptr)[i]的类型:

  • 由于intptr,所以(*ptr)[i]必须是int的数组。
  • 由于(*ptr)int的数组,所以(*ptr)必须是int的数组。
  • 由于*ptrint的数组,所以*ptr必须是指向int的数组的指针。

脚注

1 Kernighan和Ritchie, C编程语言,1978年,第90页。

,

在表达式和声明中,后缀运算符[]()的优先级均高于一元*。因此,声明

T *a[N]; // a is an array of pointer to T
T *f();  // f is a function returning pointer to T

解析为

T *(a[N]); // result of a[i] will be dereferenced
T *(f());  // result of f() will be dereferenced

如果要使用指向数组的指针或指向函数的指针,则必须将*运算符与指针表达式所组成的对象明确组合在一起:

T (*a)[N]; // result of *a will be subscripted
T (*f)();  // result of *f will be executed

指针不必是简单的标识符-您可以具有一个将指针返回数组的函数:

T (*f())[N]; // result of *f() will be subscripted

或指向函数的指针数组

T (*a[N])(); // result of *a[i] will be executed