C:查找内存块中字节的出现

C: finding occurrences of bytes in a block of memory

我正在尝试编写一个函数,它仅使用基于指针的逻辑来搜索内存区域 (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 次后停止。我对指针还是个新手,不确定我做的是否正确。

你的指针代码是正确的。

您应该将 countmaxBytes 进行比较,而不是 read

  for (read = 0; read < blockLength && count < maxBytes; read++) {
    if (*(blockAddress + read) == Byte) {
      *(pOffsets + count) = read;
      count++;
    } // if
  } // for