多维数组和指针的指针 [英] Multi-dimensional array and pointer to pointers

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

问题描述

根据我的书,创建多维数组char a[10][10]时,它表示必须使用类似于char a[][10]的参数才能将数组传递给函数.

When you create the multi-dimensional array char a[10][10], according to my book it says you must use a parameter similar to char a[][10] to pass the array to a function.

为什么必须这样指定长度?您不只是传递一个双指针指向with,并且那个双指针是否已经指向已分配的内存?那么为什么参数不能为char **a?您是否要通过提供第二个10重新分配任何新的内存?

Why must you specify the length as such? Aren't you just passing a double pointer to being with, and doesn't that double pointer already point to allocated memory? So why couldn't the parameter be char **a? Are you reallocating any new memory by supplying the second 10.

推荐答案

指针不是数组

被取消引用的char **是类型为char *的对象.

A dereferenced char ** is an object of type char *.

被取消引用的char (*)[10]是类型为char [10]的对象.

A dereferenced char (*)[10] is an object of type char [10].

数组不是指针

有关此主题的信息,请参见 c-faq条目.

See the c-faq entry about this very subject.

假设你有

char **pp;
char (*pa)[10];

并且出于争论的目的,它们都指向同一位置:0x420000.

and, for the sake of argument, both point to the same place: 0x420000.

pp == 0x420000; /* true */
(pp + 1) == 0x420000 + sizeof(char*); /* true */

pa == 0x420000; /* true */
(pa + 1) == 0x420000 + sizeof(char[10]); /* true */

(pp + 1) != (pa + 1) /* true (very very likely true) */

,这就是为什么自变量不能为char**类型的原因.另外,char**char (*)[10]是不兼容的类型,因此参数的类型(衰变数组)必须与参数(函数原型中的类型)相匹配

and this is why the argument cannot be of type char**. Also char** and char (*)[10] are not compatible types, so the types of arguments (the decayed array) must match the parameters (the type in the function prototype)

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

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