我正在编写代码,将一个数组拆分为2个不同的数组,一个数组具有偶数,一个数组具有奇数。我从文件中读取数字,将其全部放入数组中,然后正确进行拆分。这是一切正常的代码:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv){
FILE* fpointer;
if (argc >= 2){
fpointer = fopen(argv[1], "r");
}else{
printf("No filename or multiple file names given");
return 0;
}
int numElem;
fscanf (fpointer, "%d\n", &numElem);
printf("Number of elements is %d\n", numElem);
int* arr;
int numEvens;
int numOdds;
arr = (int*) malloc(numElem*sizeof(int));
for (int i = 0; i < numElem; i++){
int temp;
fscanf(fpointer, "%d", &temp);
if(temp%2 == 0){
numEvens++;
}else{
numOdds++;
}
arr[i] = temp;
}
fclose(fpointer);
printf("number of evens: %d \n number of odds: %d\n", numEvens, numOdds);
//The array is now in "arr"
int* evens;
int* odds;
evens = (int*) malloc(numEvens*sizeof(int));
odds = (int*) malloc(numOdds*sizeof(int));
int a = 0;
int b = 0;
for (int i=0; i < numElem; i++){
printf("%d\n", arr[i]);
if (arr[i]%2 == 0){
evens[a] = arr[i];
a++;
}else{
odds[b] = arr[i];
b++;
}
}
printf("EVENS: %d\n", numEvens);
for (int i=0; i < numEvens; i++){
printf("%d\n", evens[i]);
}
printf("ODDS: %d\n", numOdds);
for (int i=0; i < numOdds; i++){
printf("%d\n", odds[i]);
}
现在我有一个整齐的数组,其中包含偶数,而另一个则包含奇数。它正确输出numEvens和numOdds。然后,我尝试对其进行排序:
int temp;
int x;
int y;
for (x = 0; x < numEvens-1; x++){
for (y=x+1; y < numEvens; y++){
if (evens[y] < evens[x]){
temp = evens[y];
evens[y] = evens[x];
evens[x] = temp;
}
}
}
return 0;
}
在添加排序方法之前的输出是:
Number of elements is 8
number of evens: 5
number of odds: 3
25
10
1
99
4
2
8
10
EVENS: 5
10
4
2
8
10
ODDS: 3
25
1
7
新的输出变为:
Number of elements is 8
number of evens: 32772
number of odds: 1764530596
25
10
1
99
4
2
8
10
EVENS: 32772
10
4
2
8
10
0
0
0
0
....
0大概还会继续进行32,000次,直到我中止。我来自Java之后尝试使用C,因此内存分配对我来说是一个新主题,但是我假设它与此有关。我只是不明白在声明和打印变量后如何通过添加的代码行来更改变量。我实际上并不需要新的排序方法方面的帮助,我只想对这里发生的事情有一些了解,以便可以纠正错误。预先感谢!
答案 0 :(得分:2)
int numEvens; int numOdds;
初始化变量:
int numEvens = 0;
int numOdds = 0;
...并且不要强制转换malloc()
的结果!