ccs50uint8t

Creating an array using uint8_t (CS50 Lab4: Volume)


I am working on lab 4 of CS50 course which requires to read the header of an input file which is always 44 bytes and write it as the header of the output file. Below is the correct solution.

    const int HEADER_SIZE = 44;
// TODO: Copy header from input file to output file
    uint8_t header[HEADER_SIZE];
    fread(header, HEADER_SIZE, 1, input);
    fwrite(header, HEADER_SIZE, 1, output);

And this is how creating the uint8_t type header is explained on the course website:

You’ll likely want to create an array of bytes to store the data from the WAV file header that you’ll read from the input file. Using the uint8_t type to represent a byte, you can create an array of n bytes for your header with syntax like

uint8_t header[n];

replacing n with the number of bytes. You can then use header as an argument to fread or fwrite to read into or write from the header.

Knowing uint8_t stores 1 byte, I can not understand how we define an array of 44 bytes with it. Could you please help me on how this happens? Thank you very much! (This is my first ever question here, sorry if it is really dumb)


Solution

  • In C language there are different types of variables like int,float,double,string exc... Every variable allocates different sizes in the memory. For example if we say int x; It allocates 32-bits which means 4 bytes. In your case uint8_t allocates 1 byte. If you want to allocate 44bytes in memory you need to allocate 44 times 1 byte. By defining a uint8_t array, you are allocating 1 byte memory; and when you give the array size of 44, that means you are allocating 1 byte for each element, and totally 44*1 byte. If you declare int, that would give you 44 * 4 bytes. I hope this is clear for you.