0

As static arrays are created during compile-time, may I set the length of the array with a variable obtained through e.g. another function? I believe this is dependent on whether the compiler can be smart enough to know what value this variable will have?

Example code where I obtain the size trough snprinf(). This code is compiling without errors or warnings using gcc with the -Wall flag.

#include <stdio.h>
    
int main(void)
{
    int mac[6] = {0xAA,0xBB,0xCC,0xDD,0xEE,0xFF};
    int size = snprintf(NULL, 0, "%02X", mac[0]);
    char str[size + 1];

    snprintf(str, size + 1, "%02X", mac[0]);

    printf("%s\n", str);

    return 0;
}

Compiling and running results in:

AA

Why is this possible?

0

1 Answer 1

2

str is not a static array it is what C calls a VLA, variable length array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.