Reputation: 145
Here is my code:
#include <stdio.h>
void sort(int array[], int n)
{
int i, j, temp;
for (i = 0; i < n; i++)
{
for (j = 0; j < (n - i - 1); j++)
{
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
for (i = 0; i < n; i++)
printf("%d ", array[i]);
}
int main()
{
int n, lower, upper, numbers[500], m = 0, sub_numbers[m], k = 0, index[k];
int i;
scanf("%d %d %d", &n, &lower, &upper);
for (i = 0; i < n; i++)
{
scanf("%d", &numbers[i]);
}
for(i = 0; i < n; i++)
{
if ((numbers[i] > lower) && (numbers[i] < upper))
{
sub_numbers[m] = numbers[i];
index[k] = i;
m++;
k++;
}
}
sort(sub_numbers, m);
printf("\n");
for (i = 0; i < k; i++)
printf("%d ", index[i]);
return 0;
}
I never say that sub_numbers[m] = index[k] but in the output I get index[k] on both lines while I have to have sub_numbers on the first and indexes on the second. if I comment //index[k] = i; then both arrays are sub_numbers arrays
Upvotes: 0
Views: 43
Reputation: 753970
You have:
int n, lower, upper, numbers[500], m = 0, sub_numbers[m], k = 0, index[k];
You have UB (undefined behaviour) — sub_numbers
is a variable-length array (VLA) of size 0, and so is index
. Strict C doesn't allow arrays of size 0 (C11 §6.7.6 Array declarators ¶1,¶5). GCC does allow size zero arrays, but storing anything in them is UB.
With UB, anything is possible — there is no point in speculating on what else is happening.
You could reasonably sensibly fix your code by not defining your arrays until you've read n
from the user (and validated it for basic sanity — greater than zero, less than, for sake of argument, 65,536). You'd then write:
int n;
scanf("%d", &n); // Check success
// Check n for sanity
int numbers[n], sub_numbers[n], index[n];
You've now got three arrays that should fit on the stack of a normal desktop or server-class machine — if you've got an embedded system, you may need to be more careful. I've limited the arrays to about 3/4 MiB (each one being 1/4 MiB if the size is 65,536). If you need to process more data, you won't be reading from a user typing, and you should use dynamic memory allocation with malloc()
and friends.
Upvotes: 6
Reputation: 18838
Because you are allocating an array with a variable size withoutmalloc
-like functions. For example index[k]
with k = 0
. It will cause undefined behavior afterward. Now, if you want to allocate the array with malloc
, you can't put anything inside an array with size zero. Therefore, you can modify your code by using malloc
(if you desire dynamic size allocation) and higher values for the size of the arrays.
Upvotes: 2