I need to read unknown amount of various numbers on user's input using scanf function. That simply means the number of various integers is determined by the user by sending as many numbers as he can. Note that I read directly the numbers (I have to), as stated in following code:
int main(void)
{
int numbers[];
int error = 0;
int i = 0;
while(scanf("%i", &numbers[i++]) == 1);
for(int i = 0; i < sizeof(numbers) - 1; ++i) {
if(numbers[i] < -10000 || numbers[i] > 10000)
{
printf("%i%s", numbers[i], ", ");
}
else
{
printf("%s", "\b\b\nError: Error: Vstup je mimo interval!\n");
// Means "Input is out of range!".
// We have to write exact output to terminal as stated in HW.
i = sizeof(numbers);
error = 1;
}
}
...
}
The int error is actually a boolean value, but I am lazy to implement boolean library, so I define it as integer :D
However, the problem is elsewhere. Compiler throws me an error:
main.c:7:9: error: array size missing in ‘numbers’
int numbers[];
^
Looks like that C program need to know the allocable size of an array. I already looked into some codes others have shared there to find out basics I need to implement and while searching for the array size issue, I found this question:
C - Declaring an array with an undefined value
However, it does not solve the problem with unknown array size for direct input of unknown amount of numbers. I found nowhere exactly I need to solve. I tried to define maximum size of array to hold up to 999 numbers, but then compiler throws me this exception:
main.c:50:23: error: iteration 999u invokes undefined behavior [-Werror=aggressive-loop-optimizations]
if(numbers[j] > 0)
^
main.c:48:9: note: containing loop
for(int j = 0; j < sizeof(numbers); ++j)
^
Same for every loop used for numbers statistics (total amount, maximum, minimum, odds, evens, positives, negatives, their percentage and average). That means the array is strictly size of 999 numbers with rest of numbers being zeros. I found out a malloc function, but do not understand its usage :(
_Boolinstdbool.h._Booltype even without the<stdbool.h>header; the header providesbool,true,false(and__bool_true_false_are_defined). But your main point is that C99 has support for a boolean type, and that's correct.sizeof()returns a size in bytes. If it worked on your array (if your array definition worked), thenor(int j = 0; j < sizeof(numbers); ++j)would be trying to indexsizeof(int)times too far into the array. It would have been better if you'd shown the second lot of code, but it appears that you definedint numbers[999];which can only be indexed with values 0..998, but ifsizeof(int) == 4(most common size), then your loop would have tried indexing elements 999 .. 3995, none of which exist in the array. Hence the compiler warning.malloc()(orcalloc()) to perform dynamic allocation. Can you explain what you don't understand aboutmalloc()?