這個程序的目的是運行用戶指定的數據,所有的數據都格式化爲hw-data-3.txt,其中3可以從1到100不等。我需要遍歷指定的文件並加起來花費的總金額。每行最多有50個字符,包括\ n以及每個文件最多30行。我遇到了分段錯誤,我很確定這是一個指針問題,但我不確定它在哪裏。任何人都可以幫我找到它嗎?我的程序指針錯誤[C89]
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
char buff[255];int spent[30]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,},i,z,intbuff[]={0,0,0,0};
for(i=*argv[argc-2];i>=*argv[(argc-1)];i++)
{
sprintf(buff,"hw-data-%d.txt",i);
FILE *fp;fp=fopen(buff,"r"); /*Initializing and setting file pointer for unknown amount of files*/
buff[0]='\0';
while(!feof(fp)) /*while the end of file has not been reached for the stream continue doing these actions*/
{
fgets(&buff[0],50,fp); /*captures 1 line at a time from stream then advances the streams position*/
for(z=0;buff[z]!='\0';z++){
if(buff[z]=='$')
break; /*breaks loop at position in line where $ occurs*/}
for (i=0;i<2;i++,z++){
if (buff[z]=='0'||buff[z]=='1'||buff[z]=='2'||buff[z]=='3'||buff[z]=='4'||buff[z]=='5'||buff[z]=='6'||buff[z]=='7'||buff[z]=='8'||buff[z]=='9')
intbuff[i]=buff[z];
else
break;}/* break statement is here to preserve number of integers after $, ie. $100 i=3 $33 i=2 $9 i=1 */
for (;i>=0;--i)
{
intbuff[3]+=buff[i];
}
for(i=0;i<30;i++)
{(spent[i]==0)?(spent[i]=intbuff[3]):(0);}/* If i in int array is 0 then replace 0 with the number captured.*/
}
fclose(fp);
}
return(0);
}