I'm brushing up on some C++ and so one of the problems I'm trying to solve is counting characters from a character pointer and check it against what I expect to see. However in my solution, I noticed a peculiar result. I passed in a reference to a char to my function and it returned a count of 3. Why would the reference test return back a count of 3 for a reference to a character?
I realize the character doesn't have a null terminator and so the code keeps counting but it does eventually return a result, so that means the solution falls short. Any ideas to make it more robust? Here is my solution and result.
CountCharacters.cpp
#include <cstdio>
#include <iostream>
#define ASSERT_EQUALS(paramx1, paramx2) \
{\
int param1 = paramx1;\
int param2 = paramx2;\
if (param1==param2)\
std::cout << "PASS! param1=" << param1 << " param2=" << param2 << std::endl;\
else\
std::cout << "FAIL! param1=" << param1 << " param2=" << param2 << std::endl;\
}
int countCharacters(const char * characters);
int main()
{
char character = '1';
ASSERT_EQUALS(countCharacters("string8\0"), 7);
ASSERT_EQUALS(countCharacters("\0"), 0);
ASSERT_EQUALS(countCharacters(""), 0);
ASSERT_EQUALS(countCharacters(NULL), 0);
ASSERT_EQUALS(countCharacters(&character), 1);
ASSERT_EQUALS(countCharacters('\0'), 0);
return 0;
}
int countCharacters(const char * characters)
{
if (!characters) return 0;
int count = 0;
const char * mySpot = characters;
while (*(mySpot) != '\0')
{
std::cout << "Count=" << count << " mySpot=" << *(mySpot) << std::endl;
count++;
mySpot++;
}
return count;
}
Results:
PASS! param1=7 param2=7
PASS! param1=0 param2=0
PASS! param1=0 param2=0
PASS! param1=0 param2=0
FAIL! param1=2 param2=1
PASS! param1=0 param2=0