Home > database >  Declare a global array before main() without knowing it's size in c
Declare a global array before main() without knowing it's size in c

Time:02-25

How to declare an array without knowing its size? The size will be calculated inside the main function (buffer_size). This code is not working, the size is always 2.

I am running the code here: https://www.onlinegdb.com/online_c_compiler

#include <stdio.h>

int *data_array = NULL;


int main()
{   
    int buffer_size = 4;
    data_array = malloc(buffer_size * sizeof(int));
    int size = sizeof(data_array)/sizeof(data_array[0]);

    printf(">> Size %d\n", size);
    for(int i=0; i<size; i  ){
        printf(">> data %d\n", data_array[i]);
    }
   
    
    return 0;
}

UPD: So, the declaration of array actually working. The issue is with the way I was checking the array size.

CodePudding user response:

For starters you may not declare a variable length array with static storage duration.

Here there is declared a pointer instead of an array

int *data_array = NULL;

The result of the expression with the sizeof operator in this declaration

int size = sizeof(data_array)/sizeof(data_array[0]);

that is equivalent to

int size = sizeof( int * )/sizeof( int );

is always equal to either 2 or 1 dependent of the used system.

You already stored the size of the allocated array in the variable buffer_size.

int buffer_size = 4;
data_array = malloc(buffer_size * sizeof(int));

So use it anywhere further as for example in this statement

printf(">> Size %d\n", buffer_size);

Pay attention to that this for loop

for(int i=0; i < buffer_size; i  ){
    printf(">> data %d\n", data_array[i]);

invokes undefined behavior because the allocated array was not initialized.

  • Related