Find the Error: Pointers, Structures, and Files – Solution

It took me a while to figure out what was wrong with this month’s Exercise file. It became an obsession! Of course, I was working with a more complex version — the original code. In that code, the information is written several times to the file, and it becomes very obvious that something is wrong. But when the data is written only once, it’s tough to know whether a problem exists.

When you examine the code, you read it line-by-line, looking for common errors: stray semicolons, infinite loops, uninitialized pointers. Then you examine the various functions to ensure that they’re called properly and that all the arguments are in the right order.

In this specific code, the problem is that the data is written incorrectly to the file. Here’s the original fwrite() statement:

fwrite(&output, sizeof(output), 1, datfile);

The function’s arguments are:

  1. The location (memory address) of the data to write: &output
  2. The size of the data chunk: sizeof(output)
  3. The number of chunks to write: 1
  4. The open file handle: datfile

It all looks good, and it did to me, until I noticed that variable output is a pointer already. So you don’t need the ampersand.

Second, the sizeof operator is measuring the wrong value. Yes, the program writes a structure’s data, and that structure is referenced as a pointer, but the structure itself is what’s written to the file, not the pointer. For the fwrite() function, you specify the structure’s size, not the pointer’s size. The proper argument is sizeof(struct data), where data is the structure’s name.

The proper fwrite() statement should be:

fwrite(output, sizeof(struct data), 1, datfile);

The fwrite() function takes the information referenced by pointer output, writes the size of the structure data, one chunk, to the open file referenced by datfile.

Similarly, the fread() function later in the code must be repaired. It makes the same errors:

fread(&input, sizeof(input), 1, datfile);

The proper statement is:

fread(input, sizeof(struct data), 1, datfile);

Make these changes and the code runs as intended.

Structure pointers can get messy! The member operators change, but aside from that, you’re still dealing with structures in memory. That confusion is enough to improperly code a solution and end up with a frustrating programming puzzle.

Leave a Reply