Size of array out of range

72 views Asked by At

I'm trying to write code that reads couple of numbers from FILE in the form of x y and stores them in two arrays, and i want the function to returns the number of couples, i tried with a FILE that contains 5 couples, but it seems that FILE *ptr goes beyond and reaches the sixth lines, here is my code:

#include<stdio.h>
#include<stdlib.h>

int main()
{  
   int X[100],Y[100];
   int i=0; int Ncouple = 0 ;int M = 5;

   FILE *fptr;
   fptr = fopen("num.data", "r");
   
   if( fptr == NULL)
   {
    printf("fail");
    exit(1);
   }
   
   while(!feof(fptr))
   {
     fscanf(fptr,"%d %d",&X[i],&Y[i]);
     printf("\nX[%d] = %d Y[%d] = %d\n",i,X[i],i,Y[i]);
     i++;Ncouple++;
   }

   fclose(fptr);
   return 0;
}

When i execute i get X[6] and Y[6] but my date file contains only 5 lines. Where am i wrong ?

1

There are 1 answers

6
Vlad from Moscow On

The condition in the while statement is the reason of the behavior that you described.

while(!feof(fptr))

This condition will be equal to true after you will try already to read a non-existent record in the file.

Rewrite the while loop like

while( fscanf(fptr,"%d %d",&X[i],&Y[i]) == 2 )
{
    printf("\nX[%d] = %d Y[%d] = %d\n",i,X[i],i,Y[i]);
    i++;Ncouple++;
}

Pay attention to that instead of this line of declarations

int i=0; int Ncouple = 0 ;int M = 5;

it would be better to write

int i=0; 
int Ncouple = 0;
int M = 5;

Or at least like

int i=0, Ncouple = 0, M = 5;