fro*_*hli 1 c arrays sorting algorithm
我完成了一个给定的代码示例作为家庭作业,它在我的64位OS X设备(使用gcc编译)上工作正常.但它不会在我的Windows 8 64位机器上执行(用MinGW编译 - gcc).我在两台机器上都使用了gcc sort.c -Wall -Wextra.不执行意味着程序在无限循环中停留在第64行.此外,我认识到这发生在第64行的循环达到11 之后.
它也可以在Codepad上运行(http://codepad.org/BoLhqtzv).
我尝试使用不同的指针算术方法来访问数组,但没有一个工作.
程序对一个长度为n的数组x进行排序.在数组x中就像一个包.所以可以多次出现一个数字.函数sort获取Array x的长度,数组x上的指针和不同数字的计数(10:从0到9).诀窍是,数组muh知道数字x中出现的数字的频率.这是有效的,因为x中的数字是连续的N(自然数).
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define M 10
/* This function generates an array of random integers in the range [0,M-1] of length n. */
int* random_array(const int n) {
int *x;
int i;
x = (int*) malloc(n * sizeof(int));
srand(time(NULL ));
for (i = 0; i < n; i++) {
x[i] = rand() % M;
}
return x;
}
/* print an array. */
void print_array(const int n, const int *x) {
int i;
printf("array: ");
for (i = 0; i < n && i < 32; i++) {
printf("%d ", x[i]);
}
if (n > 32) {
printf("...");
}
printf("\n");
}
/* check if a given array is sorted in ascending order. */
void is_sorted(const int n, const int *x) {
int i;
for (i = 1; i < n; i++) {
if (x[i - 1] > x[i]) {
fprintf(stderr, "ERROR: Array is not sorted!\n");
return;
}
}
printf("Array is sorted!\n");
}
/* n is the length of the array x and m is the same m as on your exercise sheet.
* In this case m is set to 10. */
void sort(const int n, int *x, int m) {
/* allocates memory for an zero initialized array */
int *muh = (int*) calloc(m, sizeof(int));
int loop; //count variable
/*counts each number in the array*/
for(loop = 0; loop < n; loop++){
muh[x[loop]]++;
}
/*Overrides x, Each number appears muh[loop] times at the beginning of line 65*/
for(loop = 0; loop < n; loop++){
for(; muh[loop] > 0; muh[loop]--) {
*(x++) = loop;
}
}
}
int main() {
int *x;
int n;
/* set length of the arrays */
n = 1 << 5;
/* get a random integer array of length n */
x = random_array(n);
/* print the unsorted array */
print_array(n, x);
printf("\n");
printf("sorted array:\n");
/* sort x by using sort, check if it is sorted and print it out */
sort(n, x, M);
is_sorted(n, x);
print_array(n, x);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你muh有m元素的空间,但是
for(loop = 0; loop < n; loop++){
for(; muh[loop] > 0; muh[loop]--) {
*(x++) = loop;
}
}
Run Code Online (Sandbox Code Playgroud)
你循环n.如果n > m,您有未定义的行为.
* In this case m is set to 10. */
n = 1 << 5;
Run Code Online (Sandbox Code Playgroud)
表明它咬你.
它似乎适用于某些系统但不适用于其他系统,嗯,未定义的行为会为您做到这一点.