Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading