Here's a sample program:
#include <stdio.h>
void foo(int b[]){
printf("sizeof in foo: %i\n", sizeof b);
}
int main(){
int a[4];
printf("sizeof in main: %i\n", sizeof a);
foo(a);
}
The output is:
sizeof in main: 16
sizeof in foo: 8
Question is, what's the point of that syntax if it's just converted to a standard pointer at the function boundary?
Variable length arrays is a feature where we can allocate an auto array (on stack) of variable size. It can be used in a typedef statement. C supports variable sized arrays from C99 standard.
To create an array, define the data type (like int ) and specify the name of the array followed by square brackets []. To insert values to it, use a comma-separated list, inside curly braces: int myNumbers[] = {25, 50, 75, 100};
C arrays don't have an end marker. It is your responsibility as the programmer to keep track of the allocated size of the array to make sure you don't try to access element outside the allocated size. If you do access an element outside the allocated size, the result is undefined behaviour.
The biggest problem is that one can not even check for failure as they could with the slightly more verbose malloc'd memory. Assumptions in the size of an array could be broken two years after writing perfectly legal C using VLAs, leading to possibly very difficult to find issues in the code.
It's syntactic sugar: void foo(int b[])
suggests that b
is going to be used as an array (rather than a single out-parameter), even though it really is a pointer.
It's a left-over from early versions of C, where postfix []
was the syntax for a pointer declaration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With