C Array Size

Whats the difference between doing a malloc and this code? …to obtain an integer array of size n.

   int n;
   scanf("%d", &n);
   int arr[n];

Actually I was surprised that such a feature exists as it dosent exist in TurboC.Is it a new feature in gcc?

1 Like

In this code, the array size is fixed which means after declaring this statement you can’t allocate memory for any more element of this array.

Use: when you are sure that array size is fixed and it can't grow any fruther during runtime.
e.g: A class of n students where n < 100.

Whereas, malloc is used to allocate dynamic memory which means array size can grow according to the requiremnt.

Use: when you are not sure how much array size grow during runtime.
e.g: World population.

Another significant difference is that when using malloc, memory is allocated on heap, when using local variables those are in stack but heap is bigger.

This feature is called “Variable-length array” and is supported in C99 C standard.

2 Likes
  1. array size is fixed, once memory is allocated you are not allowed to change its size in the same context. where as in malloc() you can change size, by realloc().
  2. increment of array base cannot be changed, where it can be changed in malloc().
  3. local array are allocated in stack, global array are allocated in data segment. where as malloc() are allocated in heap segment.
1 Like

On my GCC compiler (TDM : 4.7.1), variable length arrays seem to work in C, C++ and C99, although I couldn’t find it in the official docs.

Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++

you forgot the ampersand in scanf()

1 Like

So now in C, can we use function first and then declare variable?

edited…:slight_smile:

malloc function is mainly used to allocate memory on run-time whereas array declaration with fixed size is used when you know the size of array during compile time.