Hashini
Hashini

Reputation: 89

C - Writing duplicate array records into a text file

In this C program i have an array with duplicate student IDs. When I try to write it to a text file, it skips the duplicate values and write the remaining data into the file with value 0 in each duplicated value. But I want to write that duplicate record also into the file.

Here's my code;

int WriteData(struct Sales StoreSales[])
{
 int i;
 FILE *fptr;

 fptr = fopen("reverseOrder.txt", "w");

 if(fptr == NULL)
 {
   printf("\nError: File cannot be opened\n");
   return -1;
 }

 fprintf(fptr, "\nStudent ID\tSales Amount\n");

 for(i = SIZE ; i > 0 ; i--)
 {
   fprintf(fptr, "%d\t\t\t%d\n", StoreSales[i].StudentID, 
   StoreSales[i].amount );
 }

 fclose(fptr);
 }

 Here's my array;

 301 -> 4
 201 -> 3
 657 -> 4
 234 -> 9
 301 -> 8
 201 -> 4

As I'm a beginner to C, I can't find out a way to solve this issue. Any helpful ideas to fix my code? Thank You!

Upvotes: 0

Views: 87

Answers (1)

user2736738
user2736738

Reputation: 30926

You are having undefined behavior accessing array index out of bound.

for(i = SIZE ; i > 0 ; i--)

will be

for(i = SIZE-1 ; i >= 0 ; i--)

In C, array indexing starts from 0. You have the array of structures with SIZE number of elements which can be accessed using indices 0,1,...SIZE-1. [0-indexing]. When you accessed the element having index SIZE you have accessed memory out of the array which you are not permitted to - resulting in undefined behavior.

Further explanation:

You might access some memory that is not owned by your program which will make your program crash (accessing memory that your program is not supposed to). Or this might change some part of memory owned by your program giving rise to Erroneous results.( If read only then it will gives rise to error).

Upvotes: 1

Related Questions