Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C turning char arrays into int behaving weird

I have a much longer char array that I am turning into integers, but I cannot figure out why it behaves weird in some spots.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main () 
{
    char x[60] = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08";
    printf("%lu\n\n", strlen(x));

    for ( int i = 0; i < strlen(x); i+=3 ) {
        char num[2];
        num[0] = (char)x[i];
        num[1] = (char)x[i+1];
        printf("%d, ", atoi(num));
    }

}

The Output:

8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 500, 773, 916, 89, 

Everything is great until.....500, 773, 916, 89...what is happening?

like image 844
Joff Avatar asked Apr 27 '16 12:04

Joff


2 Answers

As you can see atoi wants a C-String: a null terminated array of character.

So, this

    char num[2];
    num[0] = (char)x[i];
    num[1] = (char)x[i+1];

Have to be

    char num[3] = {0};
    num[0] = (char)x[i];
    num[1] = (char)x[i+1];        
    num[2] = '\0'; // this could be avoided in your specific case
like image 115
LPs Avatar answered Oct 05 '22 07:10

LPs


The need for a proper string with its null character has been posted by many.

Just wanted to add another coding idea: compound literal. (char[]) { x[i], x[i + 1], '\0' } to implement that.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
  char x[] = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08";
  size_t len = strlen(x);
  printf("%zu\n\n", len);

  for (size_t i = 0; i < len; i += 3) {
    printf("%d, ", atoi((char[] ) { x[i], x[i + 1], '\0' }));
  }
}

Output

59

8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8, 

Some other fixes made too.

like image 40
chux - Reinstate Monica Avatar answered Oct 05 '22 05:10

chux - Reinstate Monica