0

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!

12
  • 1
    Can you show the expected output? Commented Dec 2, 2017 at 16:20
  • i want to write the given array in the reverse order with all the duplicate values. @coderredoc Commented Dec 2, 2017 at 16:21
  • Can you show the output which you got? Commented Dec 2, 2017 at 16:21
  • 1
    Please post the whole program. Commented Dec 2, 2017 at 16:26
  • 1
    Yes. Which I can compile and execute. @hashini.W Commented Dec 2, 2017 at 16:29

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

5 Comments

OMG Great! It Worked! Thank You @coderredoc! :) But i would be glad enough if you could explain this issue further!
@hashini.W.: Explained
@hashini.W.: No need to be sorry. It's ok. I thought there might be some issue. Be cool.
No issues my code worked fine with the help of your answer and it left me to think twice before handling arrays :)
@hashini.W: That's great. All the best.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.