-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;
}
4

1 に答える 1

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)ところで:「可変長配列」(「int arrayb [count]」など、「count」は入力パラメーター)はおそらく悪い考えです。定数を使用して配列を初期化してください...少なくとも、すべての「基本」に慣れるまでは。

私見では...

PS: "fillArray()" はデバッガーでの "シングル ステップ" と "変数の表示" に慣れるのに最適な候補です:)

于 2013-03-01T23:19:39.180 に答える