A
Avalon1178
During a review of one of my peer's code, I ran into a section of code
that was a bit suprising to me. Its got to do with initialization of
a variable-length array. I ran a small application to convince myself
whether it works or not, and it does work---however I couldn't explain
it to myself why, so I thought I'd ask here.
The sample code is below:
char test[] = "hello world\n"; // test string, but I could easily
have retrieved this string from a file or wherever
int len = strlen(test)+1;
// line below is the code of interest
char out[len];
strncpy(out, test, len);
printf("out: %s", out);
Note that 'out' is declared on the stack, yet 'len' is a variable
whose value is not known at compile time. Why would this work? I
would think the proper way of instantiating a char array with variable
length is using new, like "char *out = new char[len]", yet somehow the
above code works. Can someone explain why this works?
that was a bit suprising to me. Its got to do with initialization of
a variable-length array. I ran a small application to convince myself
whether it works or not, and it does work---however I couldn't explain
it to myself why, so I thought I'd ask here.
The sample code is below:
char test[] = "hello world\n"; // test string, but I could easily
have retrieved this string from a file or wherever
int len = strlen(test)+1;
// line below is the code of interest
char out[len];
strncpy(out, test, len);
printf("out: %s", out);
Note that 'out' is declared on the stack, yet 'len' is a variable
whose value is not known at compile time. Why would this work? I
would think the proper way of instantiating a char array with variable
length is using new, like "char *out = new char[len]", yet somehow the
above code works. Can someone explain why this works?