I need to know if I can have variable as size of array in a loop and in a function.
NOTE: I cannot use malloc.
Using array sizes as shown below, Is it valid? Will it cause any runtime issues / crash / reset / exception.
I have 2 scenarios as shown in the code
#include <stdio.h>
typedef uint8_t Buffer_Type_1[64];
typedef uint32_t Buffer_Type_2[20];
#define NO_OF_ELEMENTS(X) (sizeof(X)/sizeof(X[0]))
#define MAX_SCOPE 5
/*Max Values */
unsigned char MAX_VALUES[] = { 10, 20, 30, 0, 50};
void parse(uint8_t buffer[], size_t no_of_elements, size_t single_element_size)
{
**// Scenario-1 : Declaration of array in a function with size as function arguments**
uint8_t buffer_copy[no_of_elements * single_element_size]; // ==> Doubt-1. Is this valid? Will it cause any runtime issues / crash / reset / exception.
// Use this buffer_copy for further processing
....
// Some memcpy related stuff
.....
}
int main(int argc, char *argv[])
{
Buffer_Type_1 copy_of_Buffer_Type_1[MAX_SCOPE] = {0}; // filled by some one else
Buffer_Type_2 copy_of_Buffer_Type_2[MAX_SCOPE] = {0}; // filled by some one else
// Make copies according to the enum values
for (size_t k = 0; k < MAX_SCOPE; k++)
{
**// Scenario-2 : Declaration of array in a loop with size as counter value/enum value**
Buffer_Type_1 temp_Buffer_Type_1[MAX_VALUES[k]]; // ==> Doubt-2. Is this valid? Will it cause any runtime issues / crash / reset / exception.
for (size_t l = 0; l < MAX_VALUES[k]; l++)
{
(void) memcpy(temp_Buffer_Type_1[l], copy_of_Buffer_Type_1[k], sizeof(copy_of_Buffer_Type_1[k]));
}
}
parse((uint8_t *)copy_of_Buffer_Type_1, NO_OF_ELEMENTS(copy_of_Buffer_Type_1), sizeof(copy_of_Buffer_Type_1[0]));
parse((uint8_t *)copy_of_Buffer_Type_2, NO_OF_ELEMENTS(copy_of_Buffer_Type_2), sizeof(copy_of_Buffer_Type_2[0]));
}