Home > Mobile >  Array declaration syntax
Array declaration syntax

Time:11-07

I have some questions regarding array declarations in C99 standard.

int n;

scanf("%d", &n);

int v[n];

Does this create an array that has different size? I know that it can be a constant or a constant variable. But I think it has to have a known value at compile time, and the size should not change.

But I saw the above mentioned syntax multiple times, and I do not know that is a defenitive bug.

The second question is in relation to arrays passed to functions.

void printing(int v[])

and

void printing(int *v)

Is there a difference between the two declarations?

CodePudding user response:

C99 introduced a concept known as Variably-Modified types. Those are types that have runtime components. The line:

int v[n];

Creates an automatic variable of array type which size is defined on runtime. Those objects are known as Variable Length Array (VLA).

This is a valid C99 syntax though it is considered an risky practice because mechanism for allocation of any automatic objects does not provide any error detection. This is especially problematic for automatic VLAs which size is not known at compilation time. Automatic object are usually allocated on stack with is a scare resource (typically a few MiB on hosted machines, kilobytes on embedded systems).

Moreover Undefined Behavior is invoked if n is non-positive.

The second question. Declarations:

void printing(T v[]);
void printing(T *v);

are typically equivalent because type of parameter of array type is automatically adjusted to a pointer type. For example int v[] and int v[10] are adjusted to int*. float A[10][10] is adjusted to float (*A)[10].

Though there are a few differences:

  • T can be incomplete when forming T *v, however it must be complete when using array type.
struct S; // incomplete type
void foo(struct S *s); // ok
void foo(struct S s[]); // error
  • it is possible tell the compiler the minimal number of elements pointer by v when using array syntax uisng static keyword
void foo(int v[static 10]);

Compiler can assume that access to v[0]...v[9] is valid.

void foo(int v[static 1]);

Tells the compiler that v is not NULL.

  •  Tags:  
  • c c99
  • Related