0

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]));

}
4
  • 1
    Yes it is fine, these are called variable-length arrays (VLA). But using them is not always best practice since they might occupy a lot of stack space. Also unrelated to your questions, you should drop the weird typedefs for arrays since it just makes the code harder to read. Commented Apr 3 at 13:20
  • Your code is a bit messy, please keep only the parts relevant to your question. Commented Apr 3 at 13:26
  • 1
    Thanks @Lundin for answering. Is it supported by all the compilers. Commented Apr 3 at 13:49
  • 1
    @TechTotie Kind of, sort of, depending on C version. stackoverflow.com/a/75107648/584518 Commented Apr 3 at 13:52

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.