Frank Tocci
Frank Tocci

Reputation: 634

C array values change as a result of printf statement?

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]);
    }
}

Upvotes: 0

Views: 1135

Answers (2)

Peter
Peter

Reputation: 36597

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.

Upvotes: 0

BitTickler
BitTickler

Reputation: 11885

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.

Upvotes: 2

Related Questions