Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of C's array syntax if it discards length data?

Tags:

arrays

c

syntax

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?

like image 519
Delyan Avatar asked May 11 '12 15:05

Delyan


People also ask

Does C support variable length arrays?

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.

What is the syntax of array in C?

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};

How does C know when an array ends?

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.

Why are variable length arrays bad?

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.


1 Answers

  1. 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.

  2. It's a left-over from early versions of C, where postfix [] was the syntax for a pointer declaration.

like image 143
Fred Foo Avatar answered Oct 15 '22 14:10

Fred Foo