首页 > 解决方案 > 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 次后停止。我对指针还是新手,不确定我所做的是否正确。

标签: cpointersbyte

解决方案


您的指针代码是正确的。

你应该比较countmaxBytes而不是read

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

推荐阅读