W
William Payne
Hello. Consider the two following code snippets:
/* Snippet one */
void convert_decimal_to_binary(int n,
std::string& binary)
{
int pos = 1;
while(pos <= n)
{
if(n & pos)
{
s = "1" + s;
}
else
{
s = "0" + s;
}
pos *= 2;
}
}
/* End snippet one */
/* Snippet two */
void convert_decimal_to_binary(int n,
char* binary)
{
int pos = 1;
while(pos <= n)
{
if(n & pos)
{
push_front('1', binary);
}
else
{
push_front('0', binary);
}
pos *= 2;
}
}
void push_front(char c, char* str)
{
char temp[strlen(str) + 1];
strcpy(temp, str);
str[0] = c;
strcat(str, temp);
}
/* End snippet two */
In, snippet one, when convert_decimal_to_binary() is called with n = 9,
the variable binary equals "1001" after it has completed, which is correct.
But in snippet two the variable binary equals "11010101" for the same
value for n (9). Where is the bug(s) in snippet two that causes the string
to
be incorrect?
// William Payne
/* Snippet one */
void convert_decimal_to_binary(int n,
std::string& binary)
{
int pos = 1;
while(pos <= n)
{
if(n & pos)
{
s = "1" + s;
}
else
{
s = "0" + s;
}
pos *= 2;
}
}
/* End snippet one */
/* Snippet two */
void convert_decimal_to_binary(int n,
char* binary)
{
int pos = 1;
while(pos <= n)
{
if(n & pos)
{
push_front('1', binary);
}
else
{
push_front('0', binary);
}
pos *= 2;
}
}
void push_front(char c, char* str)
{
char temp[strlen(str) + 1];
strcpy(temp, str);
str[0] = c;
strcat(str, temp);
}
/* End snippet two */
In, snippet one, when convert_decimal_to_binary() is called with n = 9,
the variable binary equals "1001" after it has completed, which is correct.
But in snippet two the variable binary equals "11010101" for the same
value for n (9). Where is the bug(s) in snippet two that causes the string
to
be incorrect?
// William Payne