c - C:查找内存块中出现的字节
问题描述
我正在尝试编写一个函数,它仅使用基于指针的逻辑在内存区域 ( blockAddress
) 中搜索某个字节 ( Byte
),计算出现次数,并将偏移量存储在数组 ( pOffsets
) 中。这是我到目前为止所拥有的:
// blockLength is the number of bytes in the memory region;
// Byte is the value to be searched for
// maxBytes is the maximum number of bytes that are to be copied
// Returns: the number of occurrences of Byte found in the memory region
uint32_t findOccurrencesOfByte(uint32_t *const pOffsets,
const uint8_t *const blockAddress,
uint32_t blockLength, uint8_t Byte,
uint32_t maxBytes) {
uint32_t count, read;
count = 0;
for (read = 0; read < blockLength && read < maxBytes; read++) {
if (*(blockAddress + read) == Byte) {
*(pOffsets + count) = read;
count++;
} // if
} // for
return count;
} // findOccurrencesOfByte
我不确定如何实现一个条件,即如果maxBytes == 3
出现超过 3 次,它将在记录 3 次后停止。我对指针还是新手,不确定我所做的是否正确。
解决方案
您的指针代码是正确的。
你应该比较count
,maxBytes
而不是read
。
for (read = 0; read < blockLength && count < maxBytes; read++) {
if (*(blockAddress + read) == Byte) {
*(pOffsets + count) = read;
count++;
} // if
} // for
推荐阅读
- android - 无法加载资产 Flutter
- javascript - credtis、Highcharts 中的多个链接
- javascript - 无法建立套接字连接
- sql - 使用内部连接显示来自不同表的不同列
- c - 重新分配分配的内存
- hive - SparkSQL 中的 Percentile 与 percentile_approx
- python - 在numpy数组中平滑具有粗糙边界的2D轮廓
- function - 你必须声明一个函数的类型吗?
- java - Mockito 中的 when() 是否使用严格参数验证调用?
- compiler-errors - 申请:不是程序;期望一个可以应用于参数的过程(方案)?