For one of my assignments in my C book, I have to find a way to treat characters as integers. So, I wrote a program that takes an array of characters that represent integers, add them up, and output the result. In the following program, I attempt to ‘add’ the strings ‘123’ and ‘321’ which should result in ‘444’.
To do this, I first find the distance from ‘3’, ‘2’, and ‘1’ from ‘0’, respectively. For example, ’3’ is 51 in ASCII and ‘0’ 48, so the difference (or distance) is the 3 ASCII code which translates to ETX. Refer to the table below.
ASCII table
The following is the implementation. Print statements are included for debugging purposes:
#include <stdio.h>
int main (int argc, char *argv[]) {
char *num1 = "123";
char *num2 = "321";
const char Z = 48; //value of zero
char from_z = 0;
char total[] = { 0 };
int i = 0;
//main for loop
for (i = 0; num1[i] != '' || num2[i] != ''; i++) {
from_z = num2[i] - Z; //distance from '0'
total[i] = num1[i] + from_z;
//print out contents of current index and previous
//to compare
printf("i total[%d]: %cn", i, total[i]);
printf("i - 1: total[%d]: %cn", i-1, total[i-1]);
}
printf("i: %dn", i);
total[i] = '';
return 0;
}
The Bug:
When I assign and print the newly assigned index and the previously assigned one, during the second iteration, the value of total[1]
changes from ‘4’ to ‘x01’. Yet, total[0]
and total[2]
still contain ‘4’. Check the output below. (Of course ‘x01’ would print out nothing)
i total[0]: 4
i - 1: total[-1]:
i total[1]: 4
i - 1: total[0]: 4
i total[2]: 4
i - 1: total[1]:
i: 3
As you can see, total[1] was first ‘4′, and then randomly became blank. Using the debugger, I could tell that the contents of total[1]
is x01
.
What fixed it:
Having a static array where I defined total to have 4 indices like so: char total[4] = { 0 };
, the problem was fixed. But I’d still like to know why it doesn’t work for dynamic arrays.