Dirk Bruere
Dirk Bruere

Reputation: 231

Strange C code - dynamic arrays?

I have a bit of code copied from an unknown source:

 int Len=0;
 printf("Please input the length of vector");
 scanf("%d",&Len);
 float x[Len],y[Len],sig[Len];

Now normally I believe that arrays cannot be initialized during runtime with a variable. However, this does allegedly compile. Problem is that again I do not know the compiler. Is there a C variant where this is legal? The compiler I am using, IAR C, does not like it.

I am also seeing arrays indexed from 1 rather than 0, which suggests this is translated from something like Pascal originally. Any opinions?

Upvotes: 2

Views: 218

Answers (4)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726699

Now normally I believe that arrays cannot be initialized during runtime with a variable.

That has been true before C99 standard. It is also illegal in C++ (although some compilers, such as gcc, offer this as an extension).

Is there a C variant where this is legal?

Any C99 compiler will do.

I am also seeing arrays indexed from 1 rather than 0

This is OK as well, as long as you are fine allocating an extra element, and not using element at index zero.

Note: since accessing an element past the end of an array is undefined behavior, an invalid program may appear to work and produce the desired result in your test runs. If you suspect that some array indexes may be off by one, consider running your program under a memory profiler, such as valgrind, to see if the program has hidden errors related to invalid memory access.

Upvotes: 4

Sergey L.
Sergey L.

Reputation: 22542

This is called a Variable Length Array (VLA) and is a C99 feature.

If your compiler does not recognise it on it's own then try switching C standards

Try:

--std=c99
-std=c99
--std=gnu99
-std=gnu99

The manual page of your compiler will be able to tell you the exact flag.

Upvotes: 1

LMF
LMF

Reputation: 453

In C99 this is valid and called a VLA-Array.

Upvotes: 1

Spikatrix
Spikatrix

Reputation: 20244

This was a feature introduced in C99 and are called VLAs(Variable Length Arrays). These arrays are also indexed starting from 0 not 1 and ending at length-1(Len-1 in your case) just like a normal array.

Upvotes: 2

Related Questions