473,396 Members | 1,865 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Why not the same resulting string?

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
Jul 19 '05 #1
7 3268
"William Payne" <mi**************@student.liu.se> wrote...
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?


The "snippet two" is not supposed to compile.

char temp[strlen(str) + 1];

is not C++. To declare an array in C++ you _must_ put a _constant_
expression inside the brackets.

You should probably rewrite your 'push_front' as

void push_front(char c, char* s)
{
memmove(s + 1, s, strlen(s) + 1);
*s = c;
}

then it should work OK. Make sure that you initialise the array you
use for "binary" to contain all 0s.

Victor
Jul 19 '05 #2
On Wed, 17 Sep 2003 03:05:01 +0200, "William Payne" <mi**************@student.liu.se> wrote:
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 */
For this function you need a wrapper that checks for the case of
0 as well as negative value.

Also consider a wrapper for that wrapper, namely one that returns
a string instead of taking a string by reference.

Also, 'pos' would more appropriate be named 'powerOf2' or some such.

For efficiency, consider adding characters at the end of the string,
then reversing the string.

For simplicity of coding, consider using std::bitset instead of the
above.

/* 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;
}
}
Same comments as for previous function, + this function is not very
safe: it must be called with a pointer to a sufficiently large buffer.
void push_front(char c, char* str)
{
char temp[strlen(str) + 1];
This is not standard C++, but it is allowed in C99. If you're using
a compiler that allows this by default for C++ (e.g. g++), check out
the options for enforcing standard C++. In standard C++ you could use
a std::vector<char> as temporary storage, although the best thing to
do would be to simply copy the string contents in place.
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?


At the point where you add on 'temp' you don't have a valid one-character
string in 'str'.

Jul 19 '05 #3

"Victor Bazarov" <v.********@attAbi.com> wrote in message
news:bDO9b.481595$uu5.83229@sccrnsc04...
"William Payne" <mi**************@student.liu.se> wrote...
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?


The "snippet two" is not supposed to compile.

char temp[strlen(str) + 1];

is not C++. To declare an array in C++ you _must_ put a _constant_
expression inside the brackets.

You should probably rewrite your 'push_front' as

void push_front(char c, char* s)
{
memmove(s + 1, s, strlen(s) + 1);
*s = c;
}

then it should work OK. Make sure that you initialise the array you
use for "binary" to contain all 0s.

Victor


Thanks alot for your help, Victor, your code works great. I also thank you
for pointing out my violation of the C++ standard, my compiler (GCC 3.1.1)
didn't complain about it, but now I know that I should avoid writing such
statements.

// William Payne
Jul 19 '05 #4
William Payne wrote:

Thanks alot for your help, Victor, your code works great. I also thank you
for pointing out my violation of the C++ standard, my compiler (GCC 3.1.1)
didn't complain about it, but now I know that I should avoid writing such
statements.


It will complain if you use the right options. I don't know what they
are off the top of my head, though. -Wall and -pedantic should probably
be in there, but there's also one that tells it which standard to use,
like -ansi, but I think that's for C.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #5

"Kevin Goodsell" <us*********************@neverbox.com> wrote in message
news:Td*****************@newsread4.news.pas.earthl ink.net...
William Payne wrote:

Thanks alot for your help, Victor, your code works great. I also thank you for pointing out my violation of the C++ standard, my compiler (GCC 3.1.1) didn't complain about it, but now I know that I should avoid writing such statements.


It will complain if you use the right options. I don't know what they
are off the top of my head, though. -Wall and -pedantic should probably
be in there, but there's also one that tells it which standard to use,
like -ansi, but I think that's for C.

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.


I meant version 3.3.1 and the code was compiled with -W and -Wall.

// William Payne
Jul 19 '05 #6
William Payne wrote:

I meant version 3.3.1 and the code was compiled with -W and -Wall.


Even so, it was (I believe) still compiling in "GNU C++" mode. You can
make it "Standard C++" mode with some switch, but I don't know what it
is. If you look up -ansi, it will probably give you a list of similar
switches, and one (or more) should be for standard C++ mode. It's
probably something like --std=c++98 (IIRC, -ansi is equivalent to
--std=c89).

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.

Jul 19 '05 #7

"William Payne" <mi**************@student.liu.se> wrote in message
news:bk**********@news.island.liu.se...
void push_front(char c, char* str)
A char*, huh. I'll call this with '1' and "001" and see what happens...
{
char temp[strlen(str) + 1];

strcpy(temp, str);
OK, now temp == "001".

str[0] = c;
**
Now str == "101", since you just wrote over the first character.

strcat(str, temp);


Appends temp to str, giving "101001". Not what you expected? Well it could
be even worse. If I call this with '0' and str == "", then str has no
null-terminator after str[0] = '0', so strcat can do anything it wants.

I guess you could add the line str[1] = '\0'; at the ** above, and it
might work. I would just use a string myself.
Jul 19 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Terence Parker | last post by:
I am trying to connect an e-commerce system to a payment gateway (located in Hong Kong). The gateway takes values in the form of a simple form submit - however, the results (i.e. authorisation...
12
by: zig | last post by:
I've posted this on alt.comp.lang.coldfusion, but is predominantly a javascript problem: I have a CF query which returns several rows of records. I wanted to have a checkbox on each record of...
12
by: Mary Catherine | last post by:
I have 2 scipts that I am trying to get to run on the same page. One is a time/date script, the other is a countdown script (i.e. countdown days, hours, mins until a given date). They both work...
44
by: bq | last post by:
In the code int a; int b = -1; does ANSI C guarantee that "b" is located in memory right after "a" so that "a" refers to "b"? Thanks. bq
3
by: Bill | last post by:
I have a seating chart web form that has over 50 entry field controls (tables/booths) where I use a DropDownList box to select a single company name from a single large list of organizations (200...
0
by: Dil via .NET 247 | last post by:
Fresher to .NET Aiming to produce a resulting hash of length 24 CHARACTERS, using MD5 or SHA1 Algorithms. According to the Class Libraries, the hash size for the SHA1 algorithm is 160 bits, and...
9
by: philip | last post by:
If I execute that : Dim Temp as string = "This is a text" Dim sw As StreamWriter Dim fullFileName as string = "c:\text.txt" sw = New StreamWriter(fullFilename) sw.Write(temp) sw.Close() ...
6
by: Steve | last post by:
I realize that this probably isn't a best practice, but I'm working with legacy code that has a query stored in one column of a table. Because the queries vary, the JSP page that selects a query...
6
by: Martin | last post by:
Hi all, I'd like to find a .NET Collection in which I will be able to set many keys for the same object. For example, I would like to do something like that : Dictionary<long,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.