C Programming - Arrays - Discussion

Discussion Forum : Arrays - Find Output of Program (Q.No. 3)
3.
What will be the output of the program ?
#include<stdio.h>

int main()
{
    void fun(int, int[]);
    int arr[] = {1, 2, 3, 4};
    int i;
    fun(4, arr);
    for(i=0; i<4; i++)
        printf("%d,", arr[i]);
    return 0;
}
void fun(int n, int arr[])
{
    int *p=0;
    int i=0;
    while(i++ < n)
        p = &arr[i];
    *p=0;
}
2, 3, 4, 5
1, 2, 3, 4
0, 1, 2, 3
3, 2, 1 0
Answer: Option
Explanation:

Step 1: void fun(int, int[]); This prototype tells the compiler that the function fun() accepts one integer value and one array as an arguments and does not return anything.

Step 2: int arr[] = {1, 2, 3, 4}; The variable a is declared as an integer array and it is initialized to

a[0] = 1, a[1] = 2, a[2] = 3, a[3] = 4

Step 3: int i; The variable i is declared as an integer type.

Step 4: fun(4, arr); This function does not affect the output of the program. Let's skip this function.

Step 5: for(i=0; i<4; i++) { printf("%d,", arr[i]); } The for loop runs untill the variable i is less than '4' and it prints the each value of array a.

Hence the output of the program is 1,2,3,4

Discussion:
25 comments Page 3 of 3.

Payal said:   1 decade ago
Pradeep kumar what do you mean by "But it will produce run time error or segmentation fault at *p=0; after while loop. Because accessing the memory which is not allocated or allowed. ".

Rani said:   1 decade ago
Why the function fun(4,arr) does not effect the output ?

Kaustubh said:   1 decade ago
This code causes runtime error. The function func modifies memory which is beyond the scope of the array. This can corrupt the program stack.

Pradeep Kumar said:   1 decade ago
In the function fun condition while loop is i++<n i.e it will compare the value first then increment(post increment), then enter the loop.last iteration it will assign p with address of 5th element of arr[4].so the main function arr values not effected. But it will produce run time error or segmentation fault at *p=0; after while loop.because accessing the memory which is not allocated or allowed.

PRADEEP said:   1 decade ago
Here i increment to 4 p is assigned as it is post increment. p=&a[4],so it put outside the array limit, .In the main array it is not effected.


Post your comments here:

Your comments will be displayed after verification.