c语言 - CS50恢复,何时使用缓冲液和&缓冲液?



我在CS50中解决了pset4恢复问题。虽然我解决了这个问题,但我对";缓冲区"&quot&缓冲区";。请注意";管线AAAAA""线路BBBBB";。

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
// New type to store a byte of data
typedef uint8_t BYTE;
// Number of "block size" 512
const int BLOCK_SIZE = 512;
int main(int argc, char *argv[])
{
// Check for 2 command-line arguments
if (argc != 2)
{
printf("Usage: ./recover IMAGEn");
return 1;
}
// Open card.raw file
FILE *input = fopen(argv[1],"r");
// Check for fail to open
if (input == NULL)
{
printf("Couldn't open the file.n");
return 1;
}
// Read the first 4 bytes
BYTE buffer[BLOCK_SIZE];
// Count image
int count_image = 0;
// Assign NULL to output_file
FILE *output = NULL;
// Declare filename
char filename[8];
// LINE AAAAA
while (fread(buffer, sizeof(BYTE), BLOCK_SIZE, input) == BLOCK_SIZE)
{
// Check first 4 bytes for JPEG file format
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
// Only for first image, generate new filename and write into it
if (count_image == 0)
{
// Generate a new file with sequence name
sprintf(filename, "%03i.jpg", count_image);
// Open new file
output = fopen(filename, "w");
// LINE BBBBB
fwrite (&buffer, sizeof(BYTE), BLOCK_SIZE, output);
// Add filename counter
count_image++;
}
// For subsequence new repeat JPG images
// Close output file, generate new file, and write into it
else if (count_image > 0)
{
// fclose current writing files
fclose (output);
// Generate a new file with sequence name
sprintf(filename, "%03i.jpg", count_image);
// Open new file
output = fopen(filename, "w");
// LINE BBBBB
fwrite (&buffer, sizeof(BYTE), BLOCK_SIZE, output);
// Add filename counter
count_image++;
}
}
// Not fulfill the 4 bytes JPG condition, keep writing to the same filename
else if (count_image > 0)
{
// LINE BBBBB
fwrite (&buffer, sizeof(BYTE), BLOCK_SIZE, output);
}
}
fclose(output);
fclose(input);

}

问题:为什么我们使用"&缓冲区";在线路BBBBB中而不是";缓冲区";?

我知道LINE AAAAA正在使用";缓冲区";因为BYTE缓冲区[BLOCK_SIZE]是指针或数组。所以"缓冲区";指指针的位置。

当使用buffer时,它通常会转换为第一个元素的地址。&buffer是数组的地址。

这两个地址比较相等,但类型不同。当类型很重要时,请使用匹配的类型。启用所有警告以帮助识别不正确的类型使用。


由于fread()使用void *,两者都可以。

在这种情况下,概念上使用buffer来匹配sizeof(BYTE)BLOCK_SIZE

fread(&buffer, sizeof buffer, 1, input) == 1)

fwrite(缓冲区,…(将正常工作。

最新更新