Is there any way (other than malloc
) for creating an array with a size that the user inputs?
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With