Main issue
The value of n
is undefined when it is being used to specify the size of array vet
. This is an error and a C compiler should stop you from doing this (even if it's configured to C99 or C11).[1][2]
Dynamic array (on the heap)
The preferred approach to create an array of a size that is determined at runtime is to allocate memory on the heap.[2] For this, these steps should be taken in the correct order:
- declare
n
- input
n
(also validate input: check scanf
result, also if the input has a reasonable size)
- allocate
vet
(as an int
pointer via malloc
)
... before you write to the array. BTW: Don't forget to free
the memory after having used it.
So something like this could be your basic "framework" (change UPPER_LIMIT
to your needs):
#define UPPER_LIMIT 1024 /* or enum { UPPER_LIMIT=1024 }; */
int n;
if (scanf("%d", &n) == 1) {
if (0 < n && n < UPPER_LIMIT) {
int* vet = malloc(n*sizeof *vet);
if (vet) {
/* work on vet */
}
free(vet);
}
}
Fixed-size array
Another option is to use an array of fixed dimension, then you have to check the n
from input to be within the range of the fixed array:
#define UPPER_LIMIT 1024 /* or enum { UPPER_LIMIT=1024 }; */
int n;
int vet[UPPER_LIMIT];
if (scanf("%d", &n) == 1) {
if (0 < n && n < UPPER_LIMIT) {
/* work on vet */
}
}
Secondary issue
To use newlines in the format string of scanf
causes issues discussed in Behaviour of scanf when newline is in the format string. So better switch to scanf("%d", &n);
and scanf("%d", &vet[i]);
. BTW: Don't forget to check the return value of scanf
and the input.
Footnotes
[1] It's not clear why GDB online Debugger accepts this as valid code but this could be the topic of another question.
[2] C99 supports variable-length arrays (VLA), that is a way to declare arrays with a size that is determined at runtime. For this the size variable must be defined before the array declaration with a value greater than zero. (read more in Array declaration, section Variable-length arrays). C11 incorporates variable-size arrays as a implementation defined feature - that means that standard-compliant C99 code may not be portable. There is also no consensus about the actual benefit of VLAs see for example Difficulty in understanding variable-length arrays in C
Variable-size array C99(+):
#define UPPER_LIMIT 1024 /* or enum { UPPER_LIMIT=1024 }; */
int n;
if (scanf("%d", &n) == 1) {
if (0 < n && n < UPPER_LIMIT) {
int vet[n];
/* work on vet */
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…