I'm reading an input file and writing it to a 2D integer array. All the numbers in the file have two characters.
It works good but in all the [48]–[57] elements the integers have a redundant digit (e.g., 30, 871, 447 instead of 3, 87, 44). The same problem with strtol(). The hexadecimal codes of the input file look absolutely normal in those parts.
for (int a = 0; a < d; a++)
{
for (int b = 0; b < d; b++)
{
//read two chars
uint16_t num;
fread(&num, sizeof(char) * 2, 1, inptr);
//convert to int and put to the array (it makes wrong int in 48 <= b <= 57)
arr[a][b] = atoi((char*)&num);
//skip space or line break in the input file
fseek(inptr, sizeof(char), SEEK_CUR);
}
}
What's the problem? Why do only [48]–[57] work incorrectly?
Thanks for all the comments, especially for those mentioning the \0
required for atoi
.
Using char str[3]
instead of uint16_t
removes the problem and lets convert all the numbers correctly.
for (int a = 0; a < d; a++)
{
for (int b = 0; b < d; b++)
{
char str[3];
str[2] = '\0';
fread(&str, 2, 1, inptr);
arr[a][b] = atoi(str);
fseek(inptr, 1, SEEK_CUR);
}
}