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?
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).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With