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;
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);
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
is a keyword with many meanings, and in this particular case, it means not global (paraphrasing)
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.
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.
Edit: You are just allocating memory to it, doesnt count as initialization. You need to initialize the memory to 0 after allocation.
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