指向数组语法的指针 [英] Pointer to arrays syntax

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

问题描述

我对数组指针的语法有疑问. 好吧,我们知道数组本身就是指针(我们的大学教授说的),所以为什么当我们用另一个指针(将是指向指针的指针)指向它们时,我们使用以下语法:

I have a question about syntax of pointer to arrays. Well we know arrays are pointers themselves(what our uni professor said) so why when we point to them with another pointer (which would be a pointer to pointer) we use this syntax:

int array[10]; 
int *pointer = array;

代替此语法:

int array[10];
int **pointer = &array;

虽然我知道使用malloc会是正确的,但是为什么不按常规方式使用,是编译器或语法问题还是其他地方我错了?

Although i know this would be correct using malloc but why not in the normal way, is it a compiler or syntax thing or i am wrong somewhere else??

推荐答案

我们知道数组本身就是指针

Well we know arrays are pointers themselves

不.数组不是指针.数组是数组.除非它是sizeof或一元&运算符的操作数,否则类型为"T的N元素数组"的表达式都将转换(衰变")为类型为指向T的指针"的表达式,该表达式的值将是数组第一个元素的地址.但是,除了数组元素本身之外,没有为指针预留任何存储空间.

No. Arrays are not pointers. Arrays are arrays. Except when it is the operand of the sizeof or the unary & operator, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer toT" and the value of the expression will be the address of the first element of the array. However, no storage is set aside for a pointer in addition to the array elements themselves.

因此,根据声明

int array[10];

表达式array的类型是"int的10个元素的数组";除非arraysizeof或一元&的操作数,否则它将衰减为类型int *.所以

the type of the expression array is "10-element array of int"; unless array is the operand of sizeof or unary &, it will decay to type int *. So

int *ptr = array;

有效.

&array的类型为 not int **;类型为int (*)[10]或指向int的10个元素的数组的指针".您将声明并初始化这样的指针

The type of &array is not int **; the type is int (*)[10], or "pointer to 10-element array of int". You'd declare and initialize such a pointer as

int (*ptr)[10] = &array;

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

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