0

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?

3 Answers 3

4
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];.

Sign up to request clarification or add additional context in comments.

2 Comments

I feel a little stupid as I tried increasing the size of almost everything by one apart from this. Can I ask why it turned the last digit to the first in the variable?
Try more example before concluding that it is turning the last digit to the first in the variable. You are getting out of bound.
0

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.

2 Comments

My original thoughts were that because I had four numbers, I only needed numarray[3] as it counts from 0. Is it 4 because of the need for the null terminator?
No, it's 4 because you have 4 numbers. The indices are 0-3, which gives you 4 indices.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.