C ++,多维数组 [英] C++, multidimensional array

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

问题描述

将多维数组传递给函数时,为什么C ++要求在参数li中指定除第一维之外的所有维

When a multidimensional array is passed to a function, why does C++ require all but the first dimension to be specified in parameter li

推荐答案

一个更好的方法是询问为什么C ++不需要指定第一维.

A better way to ask this is to ask why C++ doesn't require the first dimension to be specified.

原因是对于 all 数组,您无法按值将数组传递给函数.如果您尝试声明带有数组的函数,则编译器会将声明调整为相应的指针类型.

The reason is that for all arrays, you can't pass arrays by value to a function. If you try to declare a function taking an array the compiler will adjust the declaration to the corresponding pointer type.

这意味着您指定哪个维度都没有关系,因为该维度不构成函数签名的一部分.

This means that it doesn't matter what dimension you specify as the dimension doesn't form part of the function signature.

例如,这些都声明完全相同的功能.

For example, these all declare exactly the same function.

void f(int *p);
void f(int p[]);
void f(int p[10]);
void f(int p[100]);

在函数中导航由 p 指向的数组时,copmiler唯一需要的信息是数组元素的大小,即这种情况.

When navigating the array pointed to by p in the function, the only information that the copmiler needs is the size of the array elements, i.e. sizeof(int) in this case.

对于更复杂的数组,完全相同.这些都是一样的:

For more complex arrays exactly the same holds. These are all the same:

void g(Type p[][10][20]);
void g(Type (*p)[10][20]);
void g(Type p[10][10][20]);
void g(Type p[99][10][20]);

但是这些都与以下内容不同:

But these are all different from:

void g(Type p[][5][20]);

因为调整除外部数组尺寸之外的任何尺寸都会影响(至少)外部数组元素的大小,这意味着必须更改用于导航数组的指针算法.

because adjusting the dimension of anything other than the outer array dimension affects the size of (at least) the outer array's elements meaning that the pointer arithmetic for navigating the array would have to change.

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

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