Search code examples
cglobal-variablesdynamic-allocation

Declaring global variable (array) inside a function in C


I need to declare a global two-dimensional array in C.

The size of the array is determined by the width and height of a given picture.

So I first have to load the picture, and only then create the array. But if I want a variable (in this case, my array) to be global, I have to declare it at the top of the file and not inside a function.

So how can I declare a array as global when I only know its size after the execution of the main() function?

EDIT: (I've also tried the other solutions so this comments refers to all of them)@Mimisbrunnr First, thanks for the quick response!

I've tried but I can't see to make it work. I'm probably missing something stupid, but how does "array" becomes global? It says on test() that 'array' is undeclared

int *buffer;

int main() {
    int i;
    int x_size=100;
    int y_size=100;

    int * buffer = malloc(sizeof(int)*x_size*y_size);
    int ** array = malloc(sizeof(int*)*y_size);

    for(i = 0; i<y_size; i++) {
        array[i]=&buffer[i*x_size];
    }

    array[0][1] = 5;
    test();
    return 0;
}

void test(){
    printf("%d",array[0][1]);
}


Solution

  • I didn't actual execute this code, but this should get you started.

    int x_size = 100;
    int y_size = 100;
    
    int ** array;
    array = malloc(sizeof(int *)*y_size);
    for(int i = 0; i<y_size; i++)
    array[i] = malloc(sizeof(int)*x_size);
    

    larsmans made a good point.

    what about this?

    int x_size = 100;
    int y_size = 100;
    
    int * buffer = malloc(sizeof(int)*x_size*y_size);
    
    int ** array = malloc(sizeof(int *)*y_size);
    for(int i = 0; i<y_size; i++)
    array[i] = &buffer[i*x_size];
    

    It looks like you might need some basic C tutorial.

    int *buffer;
    int **array;
    int main()
    {
    int x_size=100;
    int y_size=100;
    int i;
    /*int * */ buffer = malloc(sizeof(int)*x_size*y_size);
    /*int ** */ array = malloc(sizeof(int*)*y_size);
    for(i = 0; i<y_size; i++)
     array[i]=&buffer[i*x_size];
    array[0][1] = 5;
    test();
    return 0;
    }
    void test()
    {
    printf("%d",array[0][1]);
    }