Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array with undefined length in C

Tags:

arrays

c

i was watching an exercise in my textbook that says: Create a C program that take from the keyboard an array with length "N".

The question is: In C language, how can i create an undefined length array?

Thank you all.

like image 383
AngeloP Avatar asked Oct 21 '25 16:10

AngeloP


1 Answers

Do not create an array of undefined length.

After getting the needed length N, if C99 use a VLA (Variable Length Array)

int A[N];

... or allocate memory

int *A = malloc(sizeof *A * N);
...
// use A
...
free(A);

[Edit]

Good to add validation on N before proceeding. Example:

if (N <= 0 || N >= Some_Sane_Upper_Limit_Like_1000) return;
like image 58
chux - Reinstate Monica Avatar answered Oct 24 '25 08:10

chux - Reinstate Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!