Function works properly without passing parameter to another function?

How does this code work properly? I use a function to insert an array and another function to print that array in the console but I didn’t passed the array to the function to print the array but it works fine. What is the reason for that?

program

void getArray();
void DisplayArray();

int main(void)
{
    getArray();
    DisplayArray();
    return EXIT_SUCCESS;
}

void getArray()
{
    int limit, b[10];
    printf("Enter the limit:");
    scanf("%d", &limit);
    printf("Enter the values of the array:");

    for (i = 0; i < limit; i++)
    {
        scanf("%d", &b[i]);
    }
}

void DisplayArray()
{
    int i, n, array[10];
    printf("The values of Array is: \n");
    for (i = 0; i < n; i++)
    {
        printf("%d\t", array[i]);
    }
}

Output

Enter the limit:4
Enter the values of the array2
4
6
8
The values of Array is:
2
6
8

>Solution :

The code does not work, it has undefined behavior. The function getArray reads the numbers into a local array and the function DisplayArray prints the contents of a local array that is uninitialized. It seems to behave as expected because both arrays happen to be allocated at the same address at runtime, but you cannot rely on this. The behavior is just undefined.

Leave a Reply