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?
str
is not a static array it is what C calls a VLA, variable length array.