I'm trying to go through an array of char where all the chars are numbers, convert them to int, add them together, and save them as char again.
For example,
char string1[10] ={'0','0','0','9','3','1','4','0','9','1'};
char string2[10] ={'0','0','0','4','1','7','4','2','6','5'};
should produce an end result of
char string3[10] = {'0','0','1','3','4','8','8','3','5','6'};
However, it won't convert anything from string2 properly, and for some reason just adds the previous entry in a to itself whenever the program runs.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
void main (void)
{
char string1[10] ={'0','0','0','9','3','1','4','0','9','1'};
char string2[10] ={'0','0','0','4','1','7','4','2','6','5'};
char string3[10] ={'0','0','0','0','0','0','0','0','0','0'};
long a = 0, b = 0, c = 0, carry = 0, cnt;
for (cnt = 9; cnt >= 0; cnt--)
{
printf("%c %c\n", string1[cnt], string2[cnt]);
a = atol(&string1[cnt]);
b = atol(&string2[cnt]);
c = a + b + carry;
printf("%d %d %d\n", a, b, c);
if (c > 9)
{
carry = 1;
c = c - 10;
}
string3[cnt] = c;
carry = 0;
}
printf("%s", string3);
}
And the output is:
1 5
1 -1530293461 -1530293460
9 6
91 1469252395 1469252486
0 2
91 14492459 14492550
4 4
4091 984064811 984068902
1 7
14091 -1375771861 -1375757770
3 1
314091 1388700459 1389014550
9 4
9314091 298443563 307757654
0 0
9314091 298443563 307757654
0 0
9314091 298443563 307757654
0 0
9314091 298443563 307757654
LLLL
6||,00041742650009314091
What am I missing here?