Terry Chung
Terry Chung

Reputation: 27

CS50 Wk4 How does struct know how to allocate memory

currently on wk4 and had a couple of questions I couldn't find answers to elsewhere.

Within the problem set a Bitmapinfoheader is defined as a struct with

typedef struct
{
    DWORD  biSize;
    LONG   biWidth;
    LONG   biHeight;
    WORD   biPlanes;
    WORD   biBitCount;
    DWORD  biCompression;
    DWORD  biSizeImage;
    LONG   biXPelsPerMeter;
    LONG   biYPelsPerMeter;
    DWORD  biClrUsed;
    DWORD  biClrImportant;
} __attribute__((__packed__))
BITMAPINFOHEADER;

Within the file with the code itself, we create a variable that is in this type then into that variable we read the input file.

BITMAPFILEHEADER bf;
    fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr);

What I don't understand is Sorry can't embed images in posts yet but here's the link

How can the fread know that the first two bytes are biSize, the next x bytes biWidth? How can the fread parse through the bytes and know which element to place the read bytes into?

Still a massive beginner trying to learn so thank you for your help!

Upvotes: 1

Views: 47

Answers (2)

Barmar
Barmar

Reputation: 781088

fread doesn't know anything about the struct, it just reads the number of bytes you told it to read: sizeof(BITMAPFILEHEADER) * 1 bytes. It puts those bytes into the bf variable's memory.

The assumption is that the file was previously written using a similar fwrite() call. So it write the bytes of the struct to the file, and later read those same bytes into another struct with the same declaration.

The compiler will always lay out the memory for the struct the same way, so if you write and read the struct this way you'll get back the same values. Note, however, that this is only true if you're using the same or compatible compilers. The language doesn't specify how numbers are represented in memory, this is implementation-dependent. So if you write a binary file on a Windows machine and try to read it on a Linux machine, you may not get the same data values.

Upvotes: 1

mkrieger1
mkrieger1

Reputation: 23192

fread does not know what the bytes mean. It does not parse anything. It just puts a number of bytes, sizeof(BITMAPFILEHEADER), into the memory location bf.

The compiler knows how many bytes BITMAPFILEHEADER is in size, and can replace sizeof(BITMAPFILEHEADER) by that number, which is then passed to fread.

Upvotes: 1

Related Questions