Ниже моя попытка сортировки подсчета. Я составил схему своей логики, пробежался по ней устно и подробно прокомментировал свой код. Однако мой код вызывает ошибку сегментации. Я понимаю, что ошибка сегментации представляет собой незаконный доступ к памяти, поэтому это должно означать, что одно из моих значений индекса пытается получить доступ к индексу за пределами диапазона массива. Однако я не могу понять, почему это происходит.
К счастью, мой отладчик выделяет строку ниже, которую я также отметил в комментарии, где возникает ошибка сегментации. Тем не менее, я совершенно запутался. Буду признателен за любую помощь в понимании природы этой ошибки сегментации, спасибо.
void sort(int values[], int n)
{
//create array of finite size (65536)
int countArray[INT_MAX];
//create array to eventually store sorted values
int sortedValues[n];
//loop through unsorted values to increment countArray index for each occurrence
for(int i = 0; i < n; i++) {
countArray[ values[i] ] += 1;
}
//starting index for sortedValues[]
int sortedIndex = 0;
//loop until we've reached the end of sortedValues[]
while(sortedIndex < n) {
//loop through each index value of countArray
//j represents the value
for(int j = 0; j < INT_MAX; j++) {
//how many times does the index of countArray occur in values[]?
int c = countArray[j];
//only add index j as a value to sortedValues[] if it appears in values[]
while(c > 0) {
//append j to sortedValues[]
//--SEGMENTATION FAULT OCCURS ON THE LINE BELOW--
sortedValues[sortedIndex] = j;
//decrease the count of countArray[j] once value appended to sortedValues[]
c -= 1;
//move to next index of sortedValues[]
sortedIndex += 1;
}
}
}
return;
}
int sortedValues[n];
, вы должны выделить массив, используяint* sortedValues = malloc(sizeof(int)*n);
, а затем использоватьfree(sortedValues);
для освобождения выделенной памяти. - person Ahmed Akhtar   schedule 04.05.2017sortedIndex
. - person Ahmed Akhtar   schedule 04.05.2017int
являются как отрицательными, так и положительными, поэтому логика сломается. - person Sergey Kalinichenko   schedule 04.05.2017