指向数组int(* ptr)[]的指针 [英] pointer to an array int (*ptr)[]

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

问题描述

我试图了解指向数组的指针的工作方式.一个代码片段;

I am trying to understand how a pointer to an array works. A code snippet;

#include<stdio.h> 
  
int main() 
{ 
  int arr[3] = { 0 , 8 ,10 };
  int (*ptr)[3] = &arr;
  int i = 0;
  for (i = 0; i < 3 ; i++)
  printf("Address (%p) - value( %d)\n", (*ptr+i) , *(*ptr + i));
  return 0; 
} 

星号 * 取消引用 ptr .如果 i = 1 ,为什么(* ptr + i)=第一个值不是 ptr + i 处的值.

An asterisk * derefernces the ptr . If i = 1, why is (*ptr+i) = ith value not value at ptr + i.

推荐答案

ptr 的类型为 int(*)[3] (指向数组长度3的指针)( int ). * ptr 的类型为 int [3] ( int 的数组长度3).在大多数表达式中,类型为 int [3] 的操作数将被转换为 int * (指向 int 的指针),该指针指向的第一个元素数组.表达式(* ptr + i)通过指针算术得出指向数组第 i 个元素的指针.在表达式 *(* ptr + i)中,指向数组第 i 个元素的指针被取消引用以生成 i 个元素,其类型为 int .

The type of ptr is int (*)[3] (pointer to an array length 3 of int). The type of *ptr is int[3] (array length 3 of int). In most expressions, an operand of type int[3] is converted to a int * (pointer to int) pointing to the first element of the array. The expression (*ptr+i) results in a pointer to the ith element of the array by pointer arithmetic. In the expression *(*ptr+i), the pointer to the ith element of the array is dereferenced to produce the value of the ith element of the array, which is of type int.

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

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