Search code examples
cgccatoi

Need help correcting - erratic atoi() output


I am trying to convert a string of int into an array of int.

Here is my code :

int premaster1 = 3255859;
char hashString[100];
int hashStringInput[1000];

sprintf(hashString,"%d%d%d",premaster1,300,350);
printf("\n message going inside hash function = %s\n",hashString);


for(i=0;i<strlen(hashString)+1;i++){
    hashStringInput[i] = atoi(&hashString[i]);
    printf("%d",hashStringInput[i]);
}

here is my output :

message going inside hash function = 3255859300350
274089982-18387374102472550215643330548593003505930035093003503003503503503505000

which is obviously wrong. My desire output should be :

message going inside hash function = 3255859300350
3255859300350

What am I doing wrong and how may I fix it?


Solution

  • You are passing entire strings to atoi:

    "3255859300350" // First loop iteration
    "255859300350"  // Second loop iteration
    "55859300350"
    "5859300350"
    // And so on...
    

    One solution is to use temporary buffer in loop:

    char temp [2] = { 0, 0 }; // Second element is for NUL character
    temp[0] = hashString[i];  // Copy first char
    hashStringInput[i] = atoi(temp);
    

    Also, don't use +1 with your strlen, you don't want to convert the NUL character.