Jack
Jack

Reputation: 3

Converting integer to array

So far I have written a few lines to convert an integer to an array.

#include <stdio.h>

int main(int argc, char *argv[]){
    int num = 9214;
    int count = 3;
    char numarray[3];
    int temp;

    while(num > 0){
        temp = num % 10;
        numarray[count] = temp;
        num /= 10;
        count--;
    }

    printf("Array: ");
    for(count = 0; count <= 3; count++)
    printf("%d", numarray[count]);
    printf("\n\n");
}

The output should be 9214. However, it returns as 9219. If I change the variable num 5183, it would return as 5185. It changes the last number of the array to the first number of the num variable.

Does anyone have any idea where I've messed up?

Upvotes: 0

Views: 77

Answers (3)

juan.facorro
juan.facorro

Reputation: 9930

The number has 4 digits but you are allocatting an array of size 3. The assignment to numarray[3] is invalid as well as using that expression for accessing the value since it is undefined behavior.

When you declare an array the number between square brackets specifies the maximum number of elements that the array can hold and not the value for the maximum index. Access is zero based so the possible index values in an int nums[4]; array are 0, 1, 2 and 3.

In general for any array of type arr[n], where type is a valid type and n is a literal number, valid index values go from 0 to n - 1.

Upvotes: 0

jmstoker
jmstoker

Reputation: 3475

numarray is too small.

It should be

char numarray[4];

Your while loop is overwriting memory outside of the array and your printf for loop is looking at memory outside of the array.

Upvotes: 0

ouah
ouah

Reputation: 145829

char numarray[3];

This array has 3 elements, not 4.

for(count = 0; count <= 3; count++)
    printf("%d", numarray[count]);

The printf statement accesses an element outside of the array (numarray[3] but the last element is numarray[2]). Same for numarray[count] = temp; in the while loop.

To fix your issue, just change char numarray[3]; to char numarray[4];.

Upvotes: 4

Related Questions