問題描述
我想通過 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
這篇關于C++中的靜態全局變量的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!