Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way create an array with a variable length in c?

Tags:

arrays

c

function

Is there any way (other than malloc) for creating an array with a size that the user inputs?

like image 309
rippy Avatar asked Sep 11 '12 18:09

rippy


2 Answers

It all depends on the compiler.

Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the brace-level is exited. For example:

 FILE *
 concat_fopen (char *s1, char *s2, char *mode)
 {
   char str[strlen (s1) + strlen (s2) + 1];
   strcpy (str, s1);
   strcat (str, s2);
   return fopen (str, mode);
 }

See this for more information.

like image 163
NIlesh Sharma Avatar answered Oct 26 '22 22:10

NIlesh Sharma


One way is to use a VLA (C99 defines what are called 'Variable Length Arrays').

Here is an example:

#include <stdio.h>

int use_a_vla (int n)
{
  int vla[n]; /* Array length is derived from function argument.  */

  vla[0] = 10;
  vla[n-1] = 10;

  return 0;
}

int main (void)
{
  int i;

  scanf ("%d", &i); /* User input.  */

  use_a_vla (i);
}
like image 27
ArjunShankar Avatar answered Oct 26 '22 22:10

ArjunShankar