I want to use a static pointer in a function in order to point to a number of integers. The number of integers is not yet known while programming but it is known on runtime before the function is used first. So I want to give the function a parameter n and tell it to allocate memory space for n integers to the pointer and keep this. However, I learned that static variables have to initiated in their declaration and this doesn't seem to work here because on the one hand I need the * to declare them as pointers and on the other hand I need the variable name without * to allocate memory. What would a correct declaration and initialisation be for a static pointer? I'm trying to save time or else any computer that I can afford will need years for my program. As I learned that local variables are faster than global variables and pointers sometimes faster than arrays I'm experimenting with that. The function is used billions of times even in smaller test runs so any idea to speed it up is welcome. The use of pointers should also make some functions in the program work together a bit better but if they are local and initialized every time the function is called I don't expect it to be really fast.
+2
A:
Like this:
void foo() {
static int* numbers = NULL;
if (numbers == NULL) {
// Initialize them
}
}
Be prepared for concurrency issues. Why not make it a global and have a proper init_numbers() and user_numbers() function so that you control when the init happens?
St3fan
2010-01-29 18:07:25
My big problem is that I am trying to make my program faster. I was told that pointers sometimes run faster than arrays and that local variables run faster than global ones - and that if statements are very slow, so your solution doesn't seem ideal but initialising local pointers every time doesn't either as the function is called billions of times (it is somehow the core of the program).
Amy
2010-01-29 18:20:16
This won't make your program faster. Now you are checking if it's initialized every time you call foo.
the_drow
2010-01-29 18:36:14
is there any other way?
Amy
2010-01-29 19:17:01
Pointers and arrays are the same thing in C. Use a profiler to *really* find out where your app is slow. It sounds to me like you are just guessing at this point.
St3fan
2010-01-29 21:01:53
A:
I would try something like this:
void my_proc(int n)
{
static int* my_static_pointer(0);
if (my_static_pointer == 0)
{
my_static_pointer = malloc(sizeof(int) * n);
}
// check the allocation worked and use the pointer as you see fit
}
fbrereto
2010-01-29 18:10:47