使用 uint8_t 创建数组(CS50 Lab4:Volume)

发布于 2025-01-13 21:31:14 字数 652 浏览 4 评论 0原文

我正在研究 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

望喜 2025-01-20 21:31:14

在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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文