如何在 C 或 C++ 中全局初始化数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6991409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I initialize an array globally in C or C++?
提问by cdub
I'm trying to do this:
我正在尝试这样做:
for(int k=0; k<context.size(); k++)
{
cc_no_issue[k]=0;
}
Can someone tell me how I can do that globally? Whenever I try I get these errors:
有人可以告诉我如何在全球范围内做到这一点吗?每当我尝试时,都会收到以下错误:
expected unqualified-id before "for"
k does not define a type
k does not define a type
“for”之前的预期非限定id
k 未定义类型
k 未定义类型
回答by zw324
This will do:
这将:
long cc_no_issue[100]={0};
long cc_no_issue[100]={0};
And this is the proper initialization.
这是正确的初始化。
Note: this will initialize all the contents to 0.
注意:这会将所有内容初始化为 0。
This sentence:
这个句子:
long cc_no_issue[100]={1,2};
long cc_no_issue[100]={1,2};
will set cc_no_issue[0]
to 1, cc_no_issue[1]
to 2, and the rest to 0. You could see the link above for more information.
将设置cc_no_issue[0]
为 1,设置为cc_no_issue[1]
2,其余设置为 0。您可以查看上面的链接以获取更多信息。
回答by Dietrich Epp
If you have a global array of a basic type,
如果你有一个基本类型的全局数组,
int some_array[1000];
It will automatically be initialized to zero. You do not have to initialize it. If you do need to run initialization code, you can do a hack like the following (in C++):
它将自动初始化为零。您不必对其进行初始化。如果您确实需要运行初始化代码,您可以执行如下操作(在 C++ 中):
struct my_array_initializer {
my_array_initializer() {
// Initialize the global array here
}
};
my_array_initializer dummy_variable;
If you are on GCC (or Clang), you can execute code before main
with the constructor
attribute:
如果您使用 GCC(或 Clang),则可以main
使用以下constructor
属性执行代码:
__attribute__((constructor))
void initialize_array()
{
// Initialize the global array here
}
回答by Merlyn Morgan-Graham
One way is to add a global function that:
一种方法是添加一个全局函数:
- Checks if the array is initialized
- Initializes the array if it wasn't initialized
- Returns the array
- 检查数组是否已初始化
- 如果未初始化,则初始化数组
- 返回数组
Example Code:
示例代码:
int* get_cc_no_issue()
{
if(!kIsMyArrayInitialized)
{
/* todo: somehow get "context" globally... */
for(int k = 0; k < context.size(); k++)
{
cc_no_issue[k] = 0;
}
kIsMyArrayInitialized = true;
}
return cc_no_issue;
}
This is most useful if you want non-zero initialization.
如果您想要非零初始化,这是最有用的。
For zero-initialization, see this answer to another question: Is global memory initialized in C++?
对于零初始化,请参阅另一个问题的答案: 全局内存是否在 C++ 中初始化?
回答by Lundin
All global variables (variables at file scope) are by default initialized to zero since they have static storage duration (C99 6.7.8.10). So strictly speaking, you needn't initialize them to zero, the C standard guarantees that they are zero by default.
所有全局变量(文件范围内的变量)默认初始化为零,因为它们具有静态存储持续时间(C99 6.7.8.10)。所以严格来说,你不需要将它们初始化为零,C 标准保证它们默认为零。
It is good programming practice to initialize them explicitly however, as mentioned in the answer by Ziyao Wei.
然而,正如 Ziyao Wei 的回答中提到的那样,显式初始化它们是一种很好的编程习惯。
回答by Bo Persson
No, you can't have code outside of functions.
不,你不能有函数之外的代码。
You can put it inside some function and call that from the start of main
.
您可以将它放在某个函数中并从main
.
回答by Mahesh
As @Bo Persson, do it in a function instead. But, there is already an algorithm that does it for you in C++. No need to write a hand written loop.
作为@Bo Persson,请改为在函数中执行。但是,已经有一种算法可以在 C++ 中为您完成。无需编写手写循环。
std::fill(cc_no_issue, cc_no_issue+context.size(); 0) ;
Response to your comment:
回复您的评论:
To increment every element, you can make use of std::for_eachpassing a function object as the third argument.
要增加每个元素,您可以使用std::for_each传递一个函数对象作为第三个参数。
#include <iostream>
#include <algorithm>
using namespace std;
void incrementHelper( int& a ){
++a;
}
int main(){
int ar[] = { 1,2,3,4,5 };
for_each(ar, ar+5, incrementHelper );
for( int i=0; i<sizeof(ar)/sizeof(ar[0]); ++i ){
cout << ar[i] << endl;
}
return 0;
}
Ouput:
输出:
2
3
4
5
6
for_each(ar, ar+5, incrementHelper );
for_each(ar, ar+5, incrementHelper );
For each element in the array, the algorithm is going to call the function, incrementHelper
. In C terminology,to say, it serves as a call back for each element in the array. Now the call back function, receives the passed element by reference. So, modifying the reference will modify the referrent also. See the online demo.
对于数组中的每个元素,算法将调用函数incrementHelper
。在 C 术语中,可以说,它充当数组中每个元素的回调。现在回调函数通过引用接收传递的元素。因此,修改引用也会修改引用。请参阅在线演示。
回答by iammilind
You can put the array in the constructor of a global object.
您可以将数组放入全局对象的构造函数中。
int cc_no_issue[256];
struct Init {
Init(int a, unsigned int size)
{
memset(a, 0, size);
}
};
Init arr(cc_no_issue, sizeof(cc_no_issue));
回答by john
You need to decide on the language. The machanisms for this are different in C and C++. Basically C has no method of running code before your main function starts, so you cannot do complex initialisation of an array in C. In C++ you do have some options, one is to stop using a bare array (which is a C construct anyway) and instead wrap your array inside a class, and do the initialisation inside the class constructor.
您需要决定语言。这在 C 和 C++ 中的机制是不同的。基本上 C 没有在 main 函数启动之前运行代码的方法,所以你不能在 C 中对数组进行复杂的初始化。在 C++ 中你有一些选择,一个是停止使用裸数组(无论如何这是一个 C 构造)而是将您的数组包装在一个类中,并在类构造函数中进行初始化。
CC cc_no_issue;
class CC
{
public:
CC()
{
// initialisation of array goes here
}
private:
int array[100];
};
Another way it to use a vector, and write a function to initialise the vector.
另一种方法是使用向量,并编写一个函数来初始化向量。
std::vector<int> cc_no_issue = init_vector();
std::vector<int> init_vector()
{
std::vector<int> tmp;
// initialisation of tmp goes here
return tmp;
}