C++中的静态全局变量
我想通过 malloc 方法创建一个整数数组.我希望这个数组是全局的,并且可以在我的程序中的任何地方使用.我把代码放在一个看起来像这样的头文件中:
I would like to make an array of integers via the malloc method. I want this array to be global and be used anywhere in my program. I put code in a header file that looked like this:
static int *pieces;
然后我有一个函数,用我想要的数字填充它.该函数位于命名空间中,并且该命名空间在其自己的 .cpp 文件中实现.但是,我将头文件导入 main.c 并从创建数组的命名空间调用函数,如:
Then I have a function that fills it with numbers that I want in there. The function is in a namespace and the namespace is implemented in its own .cpp file. However, I import the header file into main.c and call the function from the namespace that creates the array like:
pieces = malloc(sizeof(int) * 128);
但是当我尝试在 main 中访问数组中的数字时(在调用创建我的数组的函数之后),它崩溃并说这些部分没有被初始化.但是在我拥有的函数中,我可以创建它并很好地操纵其中的数字.我的印象是,通过使部分成为静态变量,只要任何地方的某个函数发生更改(或设置),就会影响该变量在任何地方的使用.基本上我想说的是为什么即使我在我调用的函数中设置了块,在 main 中仍然显示未设置?
But when I try to access numbers in the array in main (after calling the function that creates my array), it crashes and says that pieces wasn't initialized. But in the function I have I can create it and manipulate the numbers in it just fine. I was under the impression that by making pieces a static variable, whenever some function anywhere changes (or sets it) then that will affect the usage of the variable anywhere. Basically what I'm trying to say is why does pieces appear unset in main, even though I set it in a function that I called?
推荐答案
Static
是一个有很多含义的关键字,在这个特殊情况下,它的意思是非全局(释义)
Static
is a keyword with many meanings, and in this particular case, it means not global (paraphrasing)
这意味着每个.cpp
文件都有自己的变量副本.因此,当您在 main.cpp
中初始化时,它仅在 main.cpp
中初始化.其他文件仍未初始化.
It means that each .cpp
file has its own copy of the variable. Thus, when you initialize in main.cpp
, it is initialized ONLY in main.cpp
. The other files have it still uninitialized.
首先要解决这个问题是删除关键字static
.这将导致多重定义问题".要解决此问题,您应该在 .cpp
文件中定义变量,并在头文件中对其进行 extern 声明.
First thing to fix this would be to remove the keyword static
. That would cause the "Multiple definitions issue". To fix this you should define the variable in a .cpp
file and just extern declare it in a header file.
您只是为其分配内存,不算作初始化.分配后需要将内存初始化为0.
You are just allocating memory to it, doesnt count as initialization. You need to initialize the memory to 0 after allocation.
您可以使用 new int[128]()
而不是更冗长的 malloc
语法,这将 也执行初始化?或者你可以走简单的路(这就是它的目的)并使用 std::矢量
You can use new int[128]()
instead of your more verbose malloc
syntax, and this would perform initialization as well? Or you could take the easy road (thats what its there for) and use std::vector
相关文章