2013-03-01 125 views
-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; 
} 
+0

“观看变量”你有没有试过调试?它在哪一行抱怨? – Mahesh 2013-03-01 23:15:08

+1

你可以通过调用'fillArray()'来改变你的例子来包含'main()'吗?目前,这不是一个独立的例子,这使得几乎不可能提供任何有意义的援助。 – danfuzz 2013-03-01 23:17:18

回答

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]”,其中 “计数” 是一个输入参数)可能是一个好主意。请使用常量来初始化数组......至少在您熟悉所有“基础知识”之前。

恕我直言...

PS: “fillArray()” 是绝对一个很好的候选人用自己熟悉的 “单步执行”,并在调试器:)

相关问题