Home > OS >  Unknown Behavior of C program with variable integer array
Unknown Behavior of C program with variable integer array

Time:10-24

I have the following programming:

#include <stdio.h>

int main()
{
    int check = 0;
    int size_of_arr;
    int int_arr[size_of_arr];//Line 1
    fscanf(stdin, "%d", &size_of_arr);// Line 2
    for (int dummy = 0; dummy < size_of_arr; dummy  )
    {
        fscanf(stdin, "%d", &int_arr[dummy]);
    }
    printf("Input Success\n");
    return 0;
}

The program exists without taking input, but if Line 1 and Line 2 are interchanged, then the program successfully takes the input.

I am unable to understand why this is happening?

CodePudding user response:

You haven't initialized size_of_arr, so it causes undefined behavior

If you put line 1 before line 2, then you're creating an array with a size of size_of_arr, but because size_of_arr is uninitialized, it will cause some undefined behavior.

int int_arr[size_of_arr];//Line 1

But if put line 2 before line 1, then you're assigning a value to size_of_arr

fscanf(stdin, "%d", &size_of_arr);// Line 2

And only now you create the array, so no undefined behavior.

CodePudding user response:

your code working fine for me in both conditions

case1:-

#include <stdio.h>

int main()
{
    int check = 0;
    int size_of_arr;
    int int_arr[size_of_arr];//Line 1
    fscanf(stdin, "%d", &size_of_arr);// Line 2
    for (int dummy = 0; dummy < size_of_arr; dummy  )
    {
        fscanf(stdin, "%d", &int_arr[dummy]);
    }
    printf("Input Success\n");
    return 0;
}

output:-

5 \\size_of_arr
4  
3
2
1
2
Input Success

case2:-

#include<stdio.h>
    
int main()
{
    int check = 0;
    int size_of_arr;
    fscanf(stdin, "%d", &size_of_arr);// Line 2
    int int_arr[size_of_arr];//Line 1
    
    for (int dummy = 0; dummy < size_of_arr; dummy  )
    {
        fscanf(stdin, "%d", &int_arr[dummy]);
    }
    printf("Input Success\n");
    return 0;
}

output:-

6 \\size_of_arr
5
4
6
7
6
5
Input Success
  • Related