prgDevelop prgDevelop - 1 year ago 69
C++ Question

Why does binary saving of array in a file works? [C++]

C++ newbie here.

I'm trying to figure out the following line that writes a buffer into a file:

fOut.write((char *)&_data, sizeof(_data));

_data = array of integers...

I have a couple of questions:

  1. Is
    the address to the first element of the array?

  2. Whatever address it is, does that mean that we only save the address of the array? then how come I still can access the array after I free it?

  3. Shouldn't I pass
    ? what is the meaning of passing the size of int (in this case) and not the size of the entire array?

  4. What does casting into
    mean when dealing with addresses?

I would really appreciate some clarifications.

Answer Source

Contrary to your comment, the array must be automatic or static storage duration in order for sizeof to work.

  1. It should be just (char*)_data. The name of an array implicitly converts to a pointer to the first element.

  2. No, write expects a pointer, and stores the content found at that location, not the location's address.

  3. No. Since _data is an array, sizeof (_data) is the cumulative size of all elements in the array. If _data were a pointer (such as when an array is dynamically allocated on the heap), you would want numElems * sizeof(_data[0]). Multiplying the size of a pointer by the number of elements isn't helpful.

  4. It means that the content at that address will be treated as a series of individual bytes, losing whatever numeric meaning it might have had. This is often done to perform efficient bulk copy of data, either to and from a file, or with memcpy/memmove. The data type should be POD (plain old data) or you'll get unexpected results.

If _data is a pointer to an array allocated from the heap, as your comment suggests, then the code is badly broken. In that case, you are saving just the address, and it may appear to work if you load the file back into the same instance of your program, but that's just because it's finding the data still in memory at the same address. The data wouldn't actually be in the file, and if you re-started the program before loading the file, you'd find that the data was gone. Make the changes I mentioned in both (1) and (3) in order to save the complete array regardless of whether it's allocated automatic, static, or dynamically.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download