Reputation: 3
I am trying to write a function that uses only pointer-based logic to search through a region of memory (blockAddress
) for a certain byte (Byte
), counts the occurrences, and stores the offsets in an array (pOffsets
). Here is what I have so far:
// 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
I'm not sure how to implement a condition that if maxBytes == 3
and there are more than 3 occurrences it would stop after recording 3 times. I'm also still new to pointers and not sure if what I did is correct.
Upvotes: 0
Views: 566
Reputation: 781833
Your pointer code is correct.
You should be comparing count
to maxBytes
, not read
.
for (read = 0; read < blockLength && count < maxBytes; read++) {
if (*(blockAddress + read) == Byte) {
*(pOffsets + count) = read;
count++;
} // if
} // for
Upvotes: 3