Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Malloc with structs in C

Tags:

c

malloc

I have a struct:

struct numbers_struct {
char numbers_array[1000];
};

struct numbers_struct numbers[some_size];

After creating struct, there is an integer number as an input:

scanf("%d",&size);

I need to use malloc(size) and specify the size of the array numbers. (instead of some_size use size)

Is something like this possible in C?

like image 676
Jack Jackson Avatar asked Oct 27 '25 10:10

Jack Jackson


2 Answers

Yes it is but malloc() require the total amount of memory require for the array, not the number of elements:

struct numbers_struct* numbers = malloc(size * sizeof(*numbers));
if (numbers)
{
}

Note that you must check the return value of scanf() before using size (which is a poor name in this case) otherwise the code could be using an uninitialized variable if scanf() fails:

int number_of_elements;
if (1 == scanf("%d", &number_of_elements))
{
    struct numbers_struct* numbers =
        malloc(number_of_elements * sizeof(*numbers));
    if (numbers)
    {
        free(numbers); /* Remember to release allocated memory
                          when no longer required. */
    }
}

Variable length arrays were introduced in C99 but there are restrictions around their use (they cannot be used at file scope for example).

like image 188
hmjd Avatar answered Oct 29 '25 01:10

hmjd


May be you can do like this

 struct numbers_struct {
char numbers_array[1000];
};

scanf("%d",&size);

struct numbers_struct *numbers = malloc(sizeof(numbers_struct) * size);
like image 33
anand Avatar answered Oct 29 '25 01:10

anand



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!