尝试从字符输入读取时出现分段错误

时间:2013-03-01 23:13:40

标签: c segmentation-fault

为什么我的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;
}

1 个答案:

答案 0 :(得分:0)

1)绝对熟悉您的调试器。这可能是Visual Studio(在Windows上),gdb(在Linux上),或者是其他任何一种替代方案。你的调试器是你的朋友。请至少熟悉设置断点,单步执行代码和查看变量内容的基础知识。

2)唯一重要的代码是:

a)您为阵列分配空间的位置(例如int arrayb[count];)和

b)您正在写入或读取该阵列的所有地方。

  The moment you read data "off the edge" of your array ... game over.

3)BTW:“可变长度数组”(如“int arrayb [count]”,其中“count”是输入参数)可能是一个坏主意。请使用常量初始化数组......至少在您对所有“基础知识”感到满意之前。

... IMHO

PS: “fillArray()”绝对是一个很好的候选者,用于熟悉调试器中的“单步执行”和“查看变量”:)