tags:

views:

103

answers:

3

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
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
This won't make your program faster. Now you are checking if it's initialized every time you call foo.
the_drow
is there any other way?
Amy
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
A: 

You can initialize the pointer to null and reuse it later.

Neeraj
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