Is there a way to create a variable length array in c?

Is there a way (other than malloc ) to create an array with the size that the user enters?

+7
source share
5 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 C ++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The vault is distributed at the point of declaration and release when the brace level is completed. 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 more details.

+6
source

One way is to use VLA (C99 defines the so-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); } 
+2
source

Unless you have a VLA or alloca() , here is an extremely complex, but portable, stack technique:

 int foo(int size) { if (size <= 64*1024) { unsigned char arr[64*1024]; return bar(arr, size); } else if (size <= 1*1024*1024) { unsigned char arr[1*1024*1024]; return bar(arr, size); } else if (size <= 64*1024*1024) { unsigned char arr[64*1024*1024]; return bar(arr, size); } else return -1; // Assume it too big } int bar(unsigned char arr[], int size) { ...your code goes here... } int maincode(int size) { // Invoke bar() indirectly, allocating an array // on the stack of at least 'size' bytes return foo(size); } 

I do not particularly recommend this technique, but it will give you different sized memory blocks allocated on the stack instead of the heap.

+1
source

Well, this is pedantic, but you can write your own heap control code and call a memory allocation function other than malloc (). Hope this answer is funny, not annoying.

0
source

I assume that you are trying to avoid malloc because you do not know about realloc .

Essentially, you should do roughly what a C ++ vector does. When your array grows to a certain size, realloc it will double its size.

realloc will grow your memory block, if possible, and if this is not possible, it will be malloc new and copy the contents through.

0
source

All Articles