0

I am trying to write a program that prints the even divisors of whatever number is entered by the user. For some reason, when the user enters 10 and the program prints out:

 10 is evenly divisible by:
1, 3, 2, 27, logout

I have no idea where it is getting these numbers from. If I uncomment the second to last printf statement, I get the following:

10 is evenly divisible by:
i = 0
1, i = 1
2, i = 2
5, i = 3
32767, logout

Why is it doing this?

Here's my code:

#include <stdio.h>

int main(void ) {

    int n, i, leng = 0, arr[leng];

    printf("Enter an integer\n");
    scanf("%i",&n);

    printf("%i is evenly divisible by:\n", n);
    for (i = 1; i <= n / 2; i++) {
        if (n % i == 0) {
            arr[leng] = i;
            leng++;
        }
    }


    for (i = 0; i <= leng; i++) {
        printf("i = %i\n", i);
        printf("%i, ", arr[i]);
    }
}
2
  • 2
    you set the lenght of arr to be leng which you set to 0. This is going to break, you need to allocate it to be n/2 or similar Commented Apr 3, 2015 at 23:08
  • leng = 0, arr[leng]; Commented Apr 3, 2015 at 23:09

2 Answers 2

2
int n, i, leng = 0, arr[leng];

You declare an array of length 0 and then merrily write past its end. C- Arrays do not grow dynamically of their own. Hence, you corrupt (stack) memory and hence you find surprising behavior.

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

Comments

0

Changing the value of leng does not cause the array arr to be magically resized. arr is being created - once, at the point of definition - as an array of zero elements (not particularly useful) and never being resized from there.

All that is happening is that multiple values are being written to an array with zero elements. That is undefined behaviour. Usually in the form of overwriting memory that is adjacent to the location of that array .... which may contain variables or other program data.

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.