If I have a 2D char array:
char tempoArray[2][3]={{1,2,3}, {4,5,6}};
How can I convert each entire row to one integer value using atoi()
so that
printf("val1 %d\nval2 %d", val1, val2);
Will give me:
123
456
When you write
char tempoArray[2][3]={{1,2,3}, {4,5,6}};
your array contains small integer values like 1
, 2
, and 3
.
atoi
operates on strings, which are arrays of characters. For example, the string
"123"
consists of the three characters '1'
, '2'
, and '3'
, plus a trailing null character '\0'
.
But the digit characters '1'
, '2'
, and '3'
do not have the values 1, 2, and 3! If you hadn't known this, I encourage you to run this little program:
#include <stdio.h>
int main()
{
printf("character '1' has value %d, number 1 has value %d\n", '1', 1);
printf("character '2' has value %d, number 2 has value %d\n", '2', 2);
printf("character '3' has value %d, number 3 has value %d\n", '3', 3);
}
Since the rows of your array are not strings (they are not arrays of useful character values, and they are not null-terminated), it is not possible to simply call atoi()
on them.
Since the arrays contain integer values already, the most straightforward thing to do would be to do the arithmetic yourself, like this:
int i, j;
int val;
for(i = 0; i < 2; i++) {
val = 0;
for(j = 0; j < 3; j++) {
val = 10 * val + tempoArray[i][j];
}
printf("val: %d\n", val);
}
If you really, really wanted to call atoi
, you would have to construct an actual string from each array row, like this:
char tmpstring[4];
for(i = 0; i < 2; i++) {
for(j = 0; j < 3; j++) {
tmpstring[j] = tempoArray[i][j] + 48; /* +48 to convert dig to char */
}
tmpstring[j] = '\0';
val = atoi(tmpstring);
printf("val: %d\n", val);
}
As you can see, this is more work, and more confusing.
One more point. To make it clear what kind of conversion was going on, I wrote
tmpstring[j] = tempoArray[i][j] + 48; /* +48 to convert dig to char */
But in real code I would never write this, because that "magic number" 48 is too obscure. In real code I would always write
tmpstring[j] = tempoArray[i][j] + '0';
By definition, the value of the character '0'
is exactly the right value to add to convert the number 1 to the character '1'
, the number 2 to the character '2'
, etc.