Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]);
}

like image 766
Avenger Avatar asked Jul 31 '26 05:07

Avenger


1 Answers

create a global pointer and then malloc the space into it.

char * buffer;

int main(void) {

    buffer = malloc( /* Width * Height */ );

}
like image 84
zellio Avatar answered Aug 01 '26 19:08

zellio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!