初始化未知大小的2-D阵列 [英] Initialize 2-D array of unknown size

查看:117
本文介绍了初始化未知大小的2-D阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有字符的2-D阵列例如字符ALIST [numStrings] [最大长度] 。理想情况下,程序执行过程中我希望能够修改ALIST的即添加,修改或删除条目的内容。由于ALIST会有所变动,我不想重新编译我的程序每一个这样的变化之后修改ALIST。所以,我想在程序结束写入ALIST到一个文本文件,然后在接下来的程序运行的开始读它放回ALIST。

I have a 2-D array of characters e.g. char aList[numStrings][maxLength]. ideally, during program execution I want to be able to modify the contents of aList i.e. add, amend or delete entries. Since aList will be subject to change, I don't want to have to recompile my program after every such change to modify aList. So I want to write aList out to a text file at program end and then read it back into aList at the commencement of the next program run.

不过,我不知道在程序启动是什么numStrings的价值。 (我不使用C99,所以我不能使用VLA,并从外部文件中拿起previous字符串的数量。)我当然可以,集numStrings以人为价值高但箅子!

However, I don't know at program start what is the value of numStrings. (I am not using C99 so I can't use a VLA, and pick up a count of previous strings from an external file.) I could, of course, set numStrings to an artificially high value but that grates!

有没有一种方法来填充ALIST不知道numStrings的价值?我不认为这是(我已经看过相关的问题),但有实现我所需要的另一种方式?

Is there a way to populate aList without knowing the value of numStrings? I don't think there is (I have looked at related questions) but is there another way of achieving what I need?

推荐答案

如果你真的希望能够从电网的中间删除项目(你的问题不明确这一点),你需要某种形式的乘法联结构。这些通常用于实现稀疏数组,所以你也许可以找到一个pre-的。

If you really want to be able to remove items from the middle of the grid (your questions isn't clear on this), you'll need some kind of multiply linked structure. These are often used to implement sparse arrays, so you can probably find one pre-made.

我说的是这样的:

+---+  
| A |  
+-|\+  
  | \  
  |  \  
  |   \  
  |    \
  |     +----+----+----+  
  |     | C0 | C1 | C2 | ...  
  |     +--|-+----+--|-+  
  |        |         |
  |        |         |  
+-V--+  +--V-+       | +----+
| R0 |->|a0,0|-------+>|a0,3|--> ...
+----+  +--|-+    +--V-+----+
| R1 |-----+----->|a1,2|--> ...
+----+     |      +--|-+
 ...       V         |
          ...        V
                    ...

其中A是该对象的根节点,C是列指针数组中,R是行指针的阵列,并且每个单元指向它沿其行和列的两个下一个邻居。所有的细胞都没有明确地重新presented被假定为有一些默认值(通常为NULL或0)。

Where A is the root node of the object, C is an array of column pointers, R is an array of row pointers, and each cell points to it next neighbor along both its row and column. All cells not explicitly represented are assumed to have some default value (usually NULL or 0).

这是一个简单的想法,但一个相当挑剔的实现,有很多机会搞砸了,所以如果你可以使用一个调试库。

It is a simple idea, but a fairly picky implementation, with lots of chances to mess up, so use a debugged library if you can.

这篇关于初始化未知大小的2-D阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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