我正在尝试分配一个64字节大小的数组,然后遍历数组索引以从输入文件中读取每个字节。但是当我没有malloc()
数组索引时,循环保持在index0中(因此每次循环时,它都会将index0中的内容替换为下一个字节,而不是将每个字节放在下一个数组索引中并保持他们都是按时间顺序排列的。)
当我使用malloc()
时,它正确使用数组索引,但它是一个无限循环并使用ram的gigs。
这是我的代码:
struct BitIO {
FILE *FilePointer;
uint8_t *Buffer[64];
uint64_t BitsAvailable;
uint64_t BitsUnavailable;
} BitIO;
void Init_BitIO(const char *FileName, const char *Mode) {
BitIO.FilePointer = fopen(FileName, Mode);
malloc(sizeof(BitIO));
while (!feof(BitIO.FilePointer)) {
size_t BytesRead = 0;
for (int i = 0; i < 64; i++) {
BitIO.Buffer[i] = (uint8_t*)malloc(1);
BytesRead = fread(BitIO.Buffer[i], 1, 1, BitIO.FilePointer);
}
}
}
答案 0 :(得分:2)
如果您“尝试分配大小为64字节的数组”,则可以考虑
uint8_t Buffer[64];
而不是
uint8_t *Buffer[64];
(后者是64个指针到字节的数组)
执行此操作后,您将无需使用malloc,因为内部具有64字节数组的结构是静态分配的。 'main'循环看起来像
for (int i = 0; i < 64; i++) {
BytesRead += fread(&BitIO.Buffer[i], 1, 1,BitIO.FilePointer);
}
但是,当然,我会建议一种更有效的形式:
BytesRead = fread(BitIO.Buffer, 1, 64, BitIO.FilePointer);
答案 1 :(得分:0)
第1点
您需要将malloc()
的返回值收集到某个变量中(并在使用返回的指针之前检查malloc()
成功)以使用已分配的内存。然后,看到你的用法,我相信你对struct成员变量类型感到困惑。根据您的使用情况,您不需要uint8_t *Buffer[64];
作为结构成员。
1.1。 如果您想使用动态内存,请将结构成员更改为
uint8_t *Buffer;
你在和for
循环中
BitIO.Buffer[i] = malloc(sizeof(uint8_t)); //allocate memory
BytesRead = fread(BitIO.Buffer[i], 1, 1,BitIO.FilePointer);
或者更好的是,当您循环固定的时间时,您可以在for
循环之外的某个时间分配内存
BitIO.Buffer = malloc( 64 * sizeof(uint8_t));
然后循环读取一次一个元素。
1.2。 否则,将结构成员更改为
uint8_t Buffer[64];
完全摆脱malloc()
。
第2点:
第3点:
请malloc()
C
和{{1}}家人的回复价值see why not to cast。