C array size given by variable -
i found code today confused me. did this:
#include <stdio.h> int main(int argc, char **argv) { int x = 5; int foo[x]; foo[0] = 33; printf("%d\n", foo[0]); return 0; } my question why work?
the array foo on stack how expanded x?
i have expected thing this:
#include <stdio.h> int main(int argc, char **argv) { int x = 5; int foo[] = malloc(sizeof(int)*x); foo[0] = 33; printf("%d\n", foo[0]); free(foo); return 0; } not prettier or but, wonder.
the snippet
int foo[x]; is talking advantage of called vla (variable length array) feature. introduced in c99 standard, made optional feature in c11.
this way, can create array data structure, length given (supplied) @ run-time.
point note, though created @ runtime, gcc allocates vlas on stack memory (unlike dynamic memory allocation heap memory).
Comments
Post a Comment