-2
为什么我的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;
}
“观看变量”你有没有试过调试?它在哪一行抱怨? – Mahesh 2013-03-01 23:15:08
你可以通过调用'fillArray()'来改变你的例子来包含'main()'吗?目前,这不是一个独立的例子,这使得几乎不可能提供任何有意义的援助。 – danfuzz 2013-03-01 23:17:18