245 views
9 9 votes

What is the output of the following code?

#include <stdio.h>

void fun(int *p) {
    *p = *p + 1;
    p++;
    *p = *p + 2;
}

int main() {
    int arr[] = {5, 10, 15};

    fun(arr + 1);

    printf("%d %d %d", arr[0], arr[1], arr[2]);

    return 0;
}
  1. $\texttt{5 10 15}$
     
  2. $\texttt{5 11 15}$
     
  3. $\texttt{5 11 17}$
     
  4. $\texttt{6 12 15}$

2 Answers

0 0 votes


The function call is:

$\texttt{fun(arr + 1)}$

Here, $\texttt{arr + 1}$ means the address of $\texttt{arr[1]}$.

So, inside $\texttt{fun()}$, pointer $\texttt{p}$ initially points to $\texttt{arr[1]}$.

Initial array:

$\texttt{arr[0] = 5}$
$\texttt{arr[1] = 10}$
$\texttt{arr[2] = 15}$

First statement:

$\texttt{*p = *p + 1}$

Since $\texttt{p}$ points to $\texttt{arr[1]}$,

$\texttt{arr[1] = 10 + 1 = 11}$

Now,

$\texttt{p++}$

moves $\texttt{p}$ from $\texttt{arr[1]}$ to $\texttt{arr[2]}$.

Now,

$\texttt{*p = *p + 2}$

Since $\texttt{p}$ now points to $\texttt{arr[2]}$,

$\texttt{arr[2] = 15 + 2 = 17}$

$\texttt{arr[0]}$ remains unchanged.

Final array becomes:

$\texttt{5, 11, 17}$
 

$\therefore$ Output : $\texttt{5 11 17}$
 

Answer: C

Answer:
Position:
Show:

Related questions

6 6 votes
1 1 answer
177
177 views
GO Classes asked Jun 24
177 views
What is the output of the following code?#include <stdio.h int main() { char str[] = "HELLO"; char *p = str + 1; *(p + 2) = 'A'; printf("%s %c", str, *p); return 0; }$\te...
9 9 votes
2 2 answers
245
245 views
GO Classes asked Jun 24
245 views
What is the output of the following code?#include <stdio.h void update(int a[]) { a[0] = a[0] + a ; *(a + 1) = *(a + 1) + 5; } int main() { int arr[] = {2, 4, 6}; update(...
8 8 votes
1 1 answer
200
200 views
GO Classes asked Jun 24
200 views
What is the output of the following code?#include <stdio.h void change(char *p) { p = 'X'; *(p + 3) = '\0'; } int main() { char str[] = "GATE"; change(str); printf("%s",...
5 5 votes
1 1 answer
162
162 views
GO Classes asked Jun 24
162 views
What is the output of the following code?#include <stdio.h int main() { char str[] = {'C', 'S', 'E', '\0', 'X'}; printf("%s %c", str, str[4]); return 0; }$\texttt{CSE X}$...