4

I've dynamically allocated a 2D array, accessed w/ a double pointer, like so:

  float **heat;
  heat = (float **)malloc(sizeof(float *)*tI); // tI == 50
  int n;
  for(n = 0; n < tI; n++){ // tI == 50
            heat[n] = (float *)malloc(sizeof(float)*sections); // sections == 30
    }

After filling all of its elements with values (I'm sure they are all filled correctly), I'm trying to output it to a file like so:

fwrite(heat, sizeof(heat[tI-1][sections-1]), ((50*30)-1), ofp);

I've also just tried:

fwrite(heat, sizeof(float), ((50*30)-1), ofp);

Am I trying to output this 2D array right?

I know that my file I/O is working (the file pointer ofp is not null, and writing to the file in decimal works), but very strange characters and messages are being outputted to my output file when I try to use fwrite to write in binary.

I know that heat[tI-1][sections-1] is also indeed within the bounds of the 2D array. I was just using it because I know that's the largest element I'm holding.

My output is a lot of NULLs and sometimes strange system paths.

2 Answers 2

7

As i know you should use:

for(int n = 0; n < tI; n++)
{
  fwrite(heat[n], sizeof(float),sections, ofp);
}
Sign up to request clarification or add additional context in comments.

6 Comments

I just edited my answer with example code that looks suspiciously like I copied it directly from you, but I'd like to assure you that wasn't the case. Didn't see your answer until I had finished the edit.
@JamesHolderness @ Giswin Hmm, I'm trying this code but I'm still getting a lot of strange characters. Can I write floats to binary using fwrite? Or could I possibly be writing to the file succesfully but Notepad++ just cannot read binary?
If you want the output in a form that is human readable, that's a completely different answer. What exactly are you expecting? All the numbers in one line space separated or comma separated? One number per line or one section per line? Basically you're going to need to use something like fprintf.
I was expecting fwrite to write out to my file in human readable binary, but it's not necessary. Does it write it in non-human readable format? If so that's fine too, as long as it explains these strange characters.
Yeah. It's going to write out exactly what is stored in memory, namely the binary representation of a float, 1500 times (30 * 50).
|
5

You can't write it out in one go, because each item in the heat array is allocated a separate segment of memory. You need to loop through the heat array and save one part at a time.

You'd need to do something more like this:

for (n = 0; n < tI; n++)
  fwrite(heat[n], sizeof(float), sections, ofp);

Comments

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.