What is the explanation of the odd behaviour in the size of the array in the given code?

119 Views Asked by At
#include<stdio.h>
int main(){
    int n;
    printf("Enter the number:");
    scanf("%d",&n);
    int array[n];

    for (int i=0;i<=n;i++){
        printf("%dEnter the number:",i);
        scanf("%d",&array[i]);
    }

    for (int i=n;i>=0;i--){
        printf("%d\n",array[i]);
    }
}

Where the size is defined to given number, but then the size is getting increased in while putting values inside the loop. Expecting the array to be accepting only 5 values but it is accepting more than 5.

2

There are 2 best solutions below

8
Allan Wind On
  1. The first loop writes to array array[n] out of bounds (loop executes n+1 times). This is undefined behavior. It will likely overwrite unrelated memory and often that cause a segfault.

    Arrays in C are 0 indexed so the first element is array[0] and the last is array[n-1].

    The revised loop below is the standard idiom in C; if it's anything else a seasoned C developer will review it with extra care.

  2. The 2nd loop read out of bound array[n] (n+1). This is undefined behavior.

  3. Check that n>=1 and reasonable size otherwise you program may crash running out of stack space.

  4. Check the return value of scanf() otherwise you may be operating on uninitialized variables which is undefined behavior.

  5. Formatted your code for readability (it matters).

#include <stdio.h>

#define MAX_N 100

int main(void) {
    int n;
    printf("Enter the number:");
    if(scanf("%d", &n) != 1) {
        fprintf(stderr, "scanf() failed\n");
        return 1;
    }
    if(n <= 0 || n > MAX_N) {
        fprintf(stderr, "n is out of range\n");
        return 1;
    }
    int array[n];
    for(int i=0; i<n; i++) {
        printf("%dEnter the number:", i);
        if(scanf("%d", &array[i]) != 1) {
            fprintf(stderr, "scanf() failed\n");
            return 1;
        }
    }
    for(int i=n-1; i>=0; i--)
        printf("%d\n", array[i]);
}

example session:

Enter the number:3
0Enter the number:1
1Enter the number:2
2Enter the number:3
3
2
1
0
NeTORT On

The problem is that i will be equal 0, 1, 2, 3, 4, 5. Just count the numbers, there are 6 of them. That is why body of for-loop is executed more than 5 times.

It is very common to write for (int i = 0; i < n; i++) // ... if you want this for-loop to work n times.