在文件范围动态可变数组 [英] Variably modified array at file scope
问题描述
我想创建一个恒定的静态数组整个在我的.m文件的顶层类似这样的事情我的Objective-C实现文件中使用的:
I want to create a constant static array to be used throughout my Objective-C implementation file similar to something like this at the top level of my ".m" file:
static const int NUM_TYPES = 4;
static int types[NUM_TYPES] = {
1,
2,
3,
4 };
我打算使用 NUM_TYPES
后在文件中,所以我希望把它放在一个变量。
I plan on using NUM_TYPES
later on in the file so I wanted to put it in a variable.
然而,当我这样做,我得到的错误
However, when I do this, I get the error
动态可变类型文件范围
我推测,这可能是与数组的大小是一个变量(当我把一个整数字面那里,就像静态int型[4] 我没有得到这个消息code>)。
I gather that this may have something to do with the array size being a variable (I don't get this message when I put an integer literal there, like static int types[4]
).
我要解决这个问题,但也许我会对此都错了......我有2个目标位置:
I want to fix this, but maybe I am going about it all wrong...I have 2 goals here:
- 要拥有一个数组,在整个文件 访问
- 要封装
NUM_TYPES
为一个变量,所以我不具有相同的文字在我的文件散落不同的地方
- To have an array which is accessible throughout the file
- To encapsulate
NUM_TYPES
into a variable so I don't have the same literal scattered about different places in my file
有什么建议?
在C常见问题发现这个: http://c-faq.com/ansi/constasconst.html
推荐答案
这样做的原因警告是,<一个href=\"http://compgroups.net/comp.lang.c/Explanation-needed-for-const-int-error-variably-modified-at-file-scope\">const在C不等于常数。它的意思是只读。因此该值存储在内存中的地址,并有可能通过机code被改变。
The reason for this warning is that const in c doesn't mean constant. It means "read only". So the value is stored at a memory address and could potentially be changed by machine code.
这篇关于在文件范围动态可变数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!