创建静态全局,可变长度2D数组 [英] Creating a static global, variable length 2D array

查看:74
本文介绍了创建静态全局,可变长度2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个具有以下要求的数组:

I am trying to create an array with the following requirements:


  • 内部链接(静态全局)

  • 仅在运行时已知大小

  • 使用 [] [] 语法访问的元素

  • 存储在堆上

  • internal linkage (static global)
  • size only known at runtime
  • elements accessed using the [][] syntax
  • stored on the heap

我一直在使用以下代码来创建一个满足我几乎所有要求的VLA,但这数组仅限于当前范围,而不具有内部链接。

I have been using the following code to create a VLA which meets almost of my requirements, but this array is limited to the current scope rather than having internal linkage.

int (*array_name)[columns] = malloc( sizeof(int[rows][columns]) );

有没有办法创建一个满足我所有需求的数组?

Is there any way to create an array which meets all of my needs?

编辑-对于这种类型的变量范围,静态全局是错误的术语,内部链接是正确的。请查看该问题的注释以获取解释。

Edit - "static global" is an incorrect term for this type of variable scope, "internal linkage" is correct. Please look at the comments to this question for an explanation.

推荐答案

可以如下所述完成所请求的属性。 (不建议这样做。)

The requested properties can be accomplished as described below. (This is not a recommendation to do so.)

定义基本指针和数组大小:

Define a base pointer and an array size:

static void *MyArrayPointer;
static size_t Columns;

知道数组大小后,初始化它们:

When the array size is known, initialize them:

Columns = some value;
MyArrayPointer = malloc(Rows * Columns * sizeof(int));
if (!MyArrayPointer) ... Handle error ...

将宏定义为用作数组:

#define MyArray ((int (*)[Columns]) MyArrayPointer)

完成上述操作后,可以将数组作为 MyArray [i] [j] 来访问code>。

Once the above is complete, the array may be accessed as MyArray[i][j].

请注意,可变长度数组支持在C语言中是可选的。GCC和Clang支持它们。给定问题中显示的示例,我们假定可以使用可变长度数组。

Note that variable length array support is optional in C. GCC and Clang support them. Given the example shown in the question, we presume variable length array support is available.

此外,我很想编写 malloc 代码:

Also, I would be tempted to write the malloc code:

MyArrayPointer = malloc(Rows * sizeof *MyArray);

如果中使用的类型,这具有自动调整分配的优势MyArray 随时都会更改。

这篇关于创建静态全局,可变长度2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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