recategorized by
692 views
3 votes
3 votes

What will be the output of the following program?

#include<stdio.h>
struct _go{
    char b[20];
    char *a;
    struct _go *c;
    }x[2] = {"GATE", "2023", x+1, "GO", "Classes", x}, *p = x;
typedef struct_go go;
go* mystry(go *p, int n){
    if (n<=0) return p++;
    if(n%2) return mystry(p->c, n-1);
    else return mystry(p->c, n-2);
}
int main()
{
    printf("%s",mystry(p,2023)->a);
}
  1. GATE
  2. $2023$
  3. Run time error
  4. GO
recategorized by

1 Answer

2 votes
2 votes

Background:

In this question x is address of first element of the array x. The mathematical statement alpha % 2 returns 1 if number is odd.

Array x

Working:

When we pass p = address of first element of array and n = 2023 following operation happens:

Passed values: Whats happening inside function

n = 2023 p is pointer to first element: Subtract one from n and pass it again to mystry. Also p will be passed as p→ c which is pointer to next element of array.

n = 2022 p = address of second element of array: subtract two from current n and pass it again to mystry. Also p will be p->c which is pointer to first element of array.

n = 2020 p = address of first element of array.

n = 2018 p = address of second element of array.

n = 2016 p = address of first element of array.

… A moments later …  :)

n = 2 p = address of second element of array

n = 0 p = address of first element of array: Here as it is 0 function will return p++. Which simply means it will return p.

In printf function we are printing p->a which is 2023\0 hence 2023 will be output.

edited by
Answer:

Related questions

2 votes
2 votes
3 answers
3