atoi
is used for converting NULL-terminated strings (char*), and not characters into integer. Your col1
, col2
, are not NULL terminated strings, and the atoi
will read the memory until it gets to the NULL value (which will end the string).
If you want to change ASCII digits into numbers, you could use simple math:
int1 = col1 - '0';
col1: 4 col2: 5 col3: 6 int1: 4 int2: 54 int3: 654
All these values are stored on stack. Let's assume that stack is currently empty (it isn't, there are other locals, return address, and such things), and that top element is 0:
STACK
----------
0 <- top
Now, your col1
, col2
, col3
are placed on the stack, as you declare them:
STACK
----------
0
col1
col2
col3
And, once you assing them values, you will get following picture:
STACK
----------
0
'4'
'5'
'6'
When you call atoi(col1)
it will read '4'
, and then, 0
, which will terminate string, and it will parse only ASCII '4'
. When you call atoi(col2)
, it will read '5'
, '4'
, and then 0
, so input string will be "54"
so it will parse exactly that. Similar will hapen for all other col
variables.
Note that there is nothing magical about reading stack elements in the reverse order - actually, you are reading memory in the direct order - because on my (and probably yours) machine stack is growing downward. On some machines this would not be the case (check this link for more details), and you would get 456...
for col1
or probably just zero (atoi
will return zero if you pass non-number string as the argument).