我在readFirst((结束时遇到分段错误。 如果我输入打印语句进行检查,有时打印语句不会出现。 代码可以编译,但是当我运行它时,它只是像它应该的那样打印文件,然后它在 return 语句中给了我错误。 我不知道问题是什么,也不知道如何解决。
int readFirst(FILE *file){
int c;
int linecount = 0;
int newLineCounter = 0;
while ((c = fgetc(file)) != EOF)
{
printf("%c", c);
if(c == 'n'){
newLineCounter++;
}
linecount++;
}
file = file + ' ';
printf("check 3");
//printf("n");
printf("%i",newLineCounter);
return newLineCounter;
}
int main (int argc, char **argv)
{
char *infile = NULL;
char *outfile = NULL;
FILE *file = stdin;
FILE *text = stdout;
char ch[200];
int iFlag = 0;
int oFlag = 0;
char *iValue = NULL;
int index;
int i;
opterr = 0;
while ((i = getopt (argc, argv, "i:o:")) != -1) {
switch (i)
{
case 'i':
iFlag = 1;
infile = optarg;
break;
case 'o':
oFlag = 1;
outfile = optarg;
break;
case '?':
if(optopt == 'i') {
fprintf(stderr, "Missing mandatory input optionn");
} else if (optopt == 'o') {
fprintf(stderr, "Missing mandatory input optionn");
} else {
fprintf(stderr, "Invalid option receivedn");
}
break;
}
}
if (infile){
file = fopen(infile, "r");
if (file == NULL){
//printf("cannot open input file n");
exit(1);
}
//fprintf(file,"%s", infile);
//fprintf(file,"%s", infile);
}
printf("check 1");
int lines;
lines = readFirst(file);
printf("check 2");
printf("%i", lines);
char labels [lines][6];
int c;
int lineCount = 0;
int curCol = 0;
int flag = 0;
for(lineCount = 0; i < lines; lineCount++){
for(curCol = 0; i < 6; curCol++){
labels[lineCount][curCol] = ' ';
}
}
while(lineCount < lines && (c = fgetc(file)) != EOF){
if(flag != 0){
if(c != ' ' || c != 't'){
labels[lineCount][curCol] = c;
curCol++;
}else {
curCol = 0;
flag = 0;
}
}
if(c == 'n'){
flag = 1;
lineCount++;
}
}
printf("%i", lineCount);
for(lineCount = 0; i < lines; lineCount++){
for(curCol = 0; i < 6; curCol++){
printf("%c",labels[lineCount][curCol]);
}
}
}
问题就在这里,在内部循环中
for(lineCount = 0; i < lines; lineCount++){
for(curCol = 0; i < 6; curCol++){
printf("%c",labels[lineCount][curCol]);
}
}
变量 i 永远不会在该循环中更新,因此两个循环都将永远运行,从而导致标签的越界数组访问。