c - 如何使用类型在c中动态声明二维数组:int(*)[]? [英] how to dynamically declare a 2-d array in c using type: int(*)[ ]?

查看:45
本文介绍了c - 如何使用类型在c中动态声明二维数组:int(*)[]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾尝试使用 int**(pointer to a pointer) 和 int*[](指针数组),但我无法使用 指向数组的指针.我们如何使用指向数组的指针ma​​lloc函数在c中创建一个二维数组.

I have tried using int**(pointer to a pointer) and int*[](array of pointers) but i am unable to perform the task with pointer to an array.How can we use pointer to an array and malloc function to create an 2-d array in c.

请提供示例代码:)

推荐答案

让我们从头开始.

动态分配 T 的 N 元素数组(对于某些任意 T)的典型方法是

The typical way to dynamically allocate an N-element array of T (for some arbitrary T) is

T *p = malloc( sizeof *p * N ); // sizeof *p == sizeof (T)

这为 T 类型的 N 个对象分配了足够的空间,p 指向第一个元素

This allocates enough space for N objects of type T, with p pointing to the first element

   T *        T
   +–––+      +–––+
p: |   |–––––>|   | p[0]
   +–––+      +–––+
              |   | p[1]
              +–––+
               ...
              +–––+
              |   | p[N-1]
              +–––+

现在,将 T 替换为数组类型 - R [M]:

Now, replace T with an array type - R [M]:

R (*p)[M] = malloc( sizeof *p * N );

这为 R [M] 类型的 N 个对象分配了足够的空间 - IOW 你已经分配了一个 NxM 的 R 数组.p 仍然指向第一个元素,只是在这种情况下第一个元素本身就是一个数组.

This allocates enough space for N objects of type R [M] - IOW you’ve allocated an NxM array of R. p still points to the first element, it’s just that in this case the first element is an array in itself.

   R (*)[M]    R [M]    
   +–––+       +–––+
p: |   |––––––>|   | p[0][0]
   +–––+       + - +
               |   | p[0][1]
               + - +
                ...
               + – + 
               |   | p[0][M-1]
               +––—+
               |   | p[1][0]
               + – +
               |   | p[1][1]
               + - +
                ...
               + – +
               |   | p[1][M-1]
               +–––+
                ...
               + – +
               |   | p[N-1][M-1]
               +–––+

您可以像任何常规二维数组一样对 p 进行索引.

You’d index into p like any regular 2d array.

您可以将其扩展到更高维的数组 - 将 R 替换为另一种数组类型,例如 Q [L]:

You can extend this to higher-dimensioned arrays - replace R with another array type like Q [L]:

Q (*p)[M][L] = malloc( sizeof *p * N );

这会为 NxMxL 数组分配空间,并且您可以像任何 3d 数组一样对其进行索引p[i][j][k].

This allocates space for an NxMxL array, and again you’d index into it like any 3d array p[i][j][k].

语义在每种情况下都完全相同 - 您为 N 个对象分配空间,只是对象的类型不同.

The semantics are exactly the same in every case - you’re allocating space for N objects, it’s just that the types of the objects are different.

这篇关于c - 如何使用类型在c中动态声明二维数组:int(*)[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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