652 views
0 votes
0 votes
void fun(int *p)
{
  int q = 10;
  p = &q;
}     
   
int main()
{
  int r = 20;
  int *p = &r;
  fun(p);
  printf("%d", *p);
  return 0;
}
a>10
b>20
c>Compiler error
d>Runtime Error

2 Answers

Best answer
4 votes
4 votes

in fun() p is the copy of the main functions pointer p..hence any change in the pointer p in fun()...does not affect the pointer p in main fun()...thus when fun() returns to the main fun()..that copy of the local variables and pointers gets deleted..hence the pointer p keeps on pointing to r whose value is 20. Always remember-if we want to change a local pointer of one function inside another function, then we must pass pointer to the pointer. By passing the pointer to the pointer, we can change pointer to point to something else.

Hence option B is correct.

selected by
0 votes
0 votes
there should have been a runtime error because q is declared in function fun and with the completion of the function execution the variable q is destroyed and reference to variable q is irrelevant

Related questions

0 votes
0 votes
1 answer
1
2 votes
2 votes
1 answer
4
Hrithik Vashishtha asked Jul 4, 2022
365 views
#include <stdio.h int main () { int i, j; int a [8] = {1, 2, 3, 4, 5, 6, 7, 8}; for(i = 0; i < 3; i++) { a[i] = a[i] + 1; i++; } i ; for (j = 7; j 4; j ) { int i = j/2; ...