atoi conversion oddity

F

Feanor

I am running this in a small loop:

char charStock[3] = {recBuff[37],
recBuff[38], recBuff[39]};

for(i=0; i<3; i++) printf("%c", charStock);

record.numInStock = atoi(charStock);

printf(" %d\n", record.numInStock);

the printf returns this:

002 228
012 1212
021 2127
030 3003
009 901
014 1417
009 904
024 2415
031 3111
123 12304
022 2220
242 24228
015 1529
001 114
987 98704
011 1113
020 2005
001 122
002 206
000 24
000 25
000 10
048 4809
000 6
000 8
000 26
999 99928



....what? Help would be appreciated.
 
M

mark_bluemel

I am running this in a small loop:

char charStock[3] = [Snip]
record.numInStock = atoi(charStock);

atoi() expects a (null-terminated) string as an argument...
 
L

Lew Pitcher

I am running this in a small loop:

char charStock[3] = {recBuff[37],
recBuff[38], recBuff[39]};

for(i=0; i<3; i++) printf("%c", charStock);

record.numInStock = atoi(charStock);

printf(" %d\n", record.numInStock);

the printf returns this:

002 228 [snip]
...what? Help would be appreciated.


atoi() manipulates a string, and a string is defined as an array of
char containing a sequence of zero or more non-zero char values
followed by a char value of 0.

You give atoi() an array of three chars. If the third char (your
charStock[2]) is not 0 ('\0'), then atoi() will continue parsing
through the memory following the charStock[] array until it finds a 0
char. My guess is that the memory following charStock[2] contains
some sort of numeric string, such that the end result of itoa() is as
you have seen.

HTH
-
Lew
 
F

Feanor

I am running this in a small loop:
char charStock[3] = {recBuff[37],
recBuff[38], recBuff[39]};
for(i=0; i<3; i++) printf("%c", charStock);

record.numInStock = atoi(charStock);
printf(" %d\n", record.numInStock);
the printf returns this:
002 228 [snip]
...what? Help would be appreciated.

atoi() manipulates a string, and a string is defined as an array of
char containing a sequence of zero or more non-zero char values
followed by a char value of 0.

You give atoi() an array of three chars. If the third char (your
charStock[2]) is not 0 ('\0'), then atoi() will continue parsing
through the memory following the charStock[] array until it finds a 0
char. My guess is that the memory following charStock[2] contains
some sort of numeric string, such that the end result of itoa() is as
you have seen.

HTH
-
Lew


Ah makes sense. Thank you much!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top