为什么我的 fillArray 函数代码导致我在运行它时遇到分段错误。我正在尝试从该函数中的字符输入中读取。为了帮助我解决这个问题,我将发布我的其他函数以及 fillArray 函数
#include <stdio.h> /* standard header file */
#include "Assg6.h"
void fillArray(int *array, int*count, char *buf){
*count = 0;
while(*buf){
*(array++) = *(buf++);
(*count)++;
}
}
void printArray(const int *array, int count, FILE *fpout){
int i;
for(i = 0; i <= count; i++){
fprintf(fpout, "%d ", *(array + i));
}
}
int findMajority(int *array, int count, int *result){
int arrayb[count];
int i, counter, bcount = 0, ccount = 0, candidate, j;
if(count % 2 != 0){
int temp = *(array + count);
for(i = 0; i <= count; i++){
if(*(array + i) == temp){
counter++;
}
}
if(counter > (count/2)){
*result = temp;
return true;
}
else{
count--;
}
}
for(j=0; j <= count; j += 2){
if(*(array + j) == *(array + j) +1){
arrayb[bcount] = *(array + j);
bcount++;
}
}
if(bcount == 1)
candidate = arrayb[0];
else
findMajority(arrayb, bcount, result);
for(j=0; j <= count; j += 2){
if(*(array + j) == candidate){
ccount++;
}
}
if(ccount > (count/2))
return true;
else
return false;
}
这是主要功能:
#include <stdio.h> // standard header file
#include <stdlib.h> // for the exit() function
#define LEN 80 // used in fgets() function
int main(int argc, char *argv[]) {
FILE *fpin, *fpout;
int a[LEN], count, majorityExists;
char buf[LEN];
int candidate;
if (argc != 3) {
printf("Usage: Assg6 InputFileName OutputFileName\n");
exit(1);
}
if ( (fpin = fopen(argv[1], "r")) == NULL) {
printf("Input file %s cannot be opened\n", argv[1]);
exit(1);
}
if ( (fpout = fopen(argv[2], "w")) == NULL) {
printf("Output file %s cannot be opened\n", argv[2]);
exit(1);
}
while (fgets(buf, LEN, fpin) != NULL) { // for each line in the input file
fillArray(a , &count, buf);
printArray(a, count, fpout);
majorityExists = findMajority(a, count, &candidate);
if (majorityExists)
fprintf(fpout, "\thas the majority element %d\n\n", candidate);
else
fprintf(fpout, "\tdoes not have a majority element\n\n");
}
fclose(fpin);
fclose(fpout);
return 0;
}