Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading