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?

1. main returns an int, not void.

2. None of your strings have a \0 at the end, so things like printf with %s, and atol are going to be disappointed.

3. a = atol(&string1[cnt]);
I rather suspect you want just the digit value, in which case it would be
a = string1[cnt] - '0';

The reverse when you store in string3 is to add '0'

>>The reverse when you store in string3 is to add '0'
Marauder: Note that you can only store a single digit using this -- '0' through '9'. Doesn't work for numeric values 10 and above or negative numbers.

>>char string1[10] ={'0','0','0','9','3','1','4','0','9','1'};
Well that's one way to do it -- and the hardest way too. This is easier to type and creates standard null-terminated string that can be used with all standard c and c++ library fundtions. char string1[] ="0009314091";

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.