質問

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?

役に立ちましたか?

解決

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.

他のヒント

Instead of below statement

   hashStringInput[i] = atoi(&hashString[i]);

Use this statement

   hashStringInput[i] =hashString[i]-'0';

Specifically In your case you can use as above and this converts ascii digit to integer digit.

  Example '3' to 3. 

atoi takes a char* and converts it to an integer. However your integer is larger than the maximum value that can be represented by an int. This causes undefined behaviour (in your case atoi returns 0x7fffffff for the first int)

Your code just makes no sense. The atoi function converts a string into an integer. So why are you passing it individual characters?

Update: You don't have a large integer. You have a string of digits. Digits represent a number from 0 to 9 inclusive, which is not large at all. And if you did have a large integer, you would never be calling atoi because that converts strings to integers.

Your code, sprintf(hashString,"%d%d%d",premaster1,300,350); creates a string of decimal digits from three integers. That's, I assume, why you call it hashString. It is not a large integer. Do not confuse numbers with their textual representations. Programmers must keep these things straight or pain will result. Half the solution is understanding the problem.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top