C: поиск байтов в блоке памяти - PullRequest
0 голосов
/ 01 апреля 2020

Я пытаюсь написать функцию, которая использует только логику на основе указателя 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-х записей. Я также все еще плохо знаком с указателями и не уверен, что то, что я сделал, правильно.

1 Ответ

3 голосов
/ 01 апреля 2020

Ваш код указателя правильный.

Вы должны сравнивать count с maxBytes, а не read.

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