使用 uint8_t 创建数组(CS50 Lab4:Volume)
我正在研究 CS50 课程的实验 4,该实验需要读取始终为 44 字节的输入文件的标头,并将其写入输出文件的标头。下面是正确的解决方案。
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);
课程网站上解释了如何创建 uint8_t 类型标头:
您可能希望创建一个字节数组来存储将从输入文件读取的 WAV 文件标头中的数据。使用 uint8_t 类型来表示一个字节,您可以使用类似于
uint8_t header[n]; 的语法为标头创建一个包含 n 个字节的数组;
将 n 替换为字节数。然后,您可以使用 header 作为 fread 或 fwrite 的参数来读取或写入 header。
知道 uint8_t 存储 1 个字节,我无法理解我们如何用它定义一个 44 字节的数组。您能帮我看看这是怎么发生的吗?非常感谢! (这是我在这里的第一个问题,抱歉,如果它真的很愚蠢)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在C语言中,有不同类型的变量,如int、float、double、string exc...每个变量在内存中分配不同的大小。例如,如果我们说 int x;它分配 32 位,即 4 个字节。在你的情况下 uint8_t 分配 1 个字节。如果要在内存中分配 44 字节,则需要分配 44 乘以 1 字节。通过定义 uint8_t 数组,您将分配 1 字节内存;当你给数组大小为 44 时,这意味着你为每个元素分配 1 个字节,总共 44*1 个字节。如果您声明 int,则将为您提供 44 * 4 字节。我希望这对你来说很清楚。
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.