I just started learning the very basics of c++, I have experience with vb.net and c#
Now I thought to get the basics covered some Project euler problems would be a good excercise. I ran into a very strange problem by trying to solve Problem 4, probably because of a lack of understanding of c++ yet.
I got 2 scenario’s, one is working, one is not(> the a variable just jumps from 999 to 768 when the sprintf command is executed as shown below), now my question is: Why is this happening in solution 1? The only difference is the loop variables a and b are declared before the loop as in solution 2 they are declared with the loop.
Solution 1 (not working):
int a =999;
int b =999;
int lb = 100;
int c = 0;
char strNumber[6];
int result = 0;
int ra = 0;
int rb = 0;
for (a=999; a>=100; a--){
for (b = a; b>=lb; b--){
c = a * b;
sprintf(strNumber, "%d", c);
if (isPalindrome(strNumber)){
if (c > result){
result = c;
lb = b;
rb = b;
ra = a;
}
b = 0;
}
}
}
Solution 2 (working):
int lb = 100;
int c = 0;
char strNumber[6];
int result = 0;
int ra = 0;
int rb = 0;
for (int a=999; a>=100; a--){
for (int b = a; b>=lb; b--){
c = a * b;
sprintf(strNumber, "%d", c);
if (isPalindrome(strNumber)){
if (c > result){
result = c;
lb = b;
rb = b;
ra = a;
}
b = 0;
}
}
}
The first time through the loop,
cis going to be a 6-digit number (999²).The
sprintf(strNumber, "%d", c);will thus write 7 chars tostrNumber: the six digits and the famous null terminator. Since you only reserved six chars forstrNumber, that last write will clobber something.It happens not to appear to clobber something important in your second case, but that’s just “luck”, your code’s behavior is undefined in both cases.
Reserve an extra char in
strNumberand both versions should work the same as far as I can tell.