Sunday, November 4, 2018

C Pointer - Predict output- Answer

Predict Program Output Based on C Pointers

Output of following C Programs are not very simple. These are simple but very interesting top c programs asked during viva and interviews.


Program-1


#include<stdio.h> 
int main() 
{ 
    int x = 10, *y, *z; 
    y = &x;  
    z = y; 
    printf("%d, %d, %d", x, *y, *z); 
    return 0; 
}

Output: 10, 10, 10
Justification: Address of variable x is assigned to pointer variable y. *y means value stored at memory address stored in y which is 10. Value stored in pointer y is stored in z; hence z also prints 10, resulting in output 10, 10, 10.

Program-2

#include "stdio.h" 
int main() 
{ 
    char str[] = { 'A', 'B', 'C', 'D' }; 
    char *p = &str[1]; 
    *p++;
    printf("%c ", *p);
    *p++;
    printf("%c ", *p);
} 

Output: C D
Justification: Address of str[1] with value 'B' is stored in pointer p; which is incremented by one and printing 'C' first and then 'D'.


Program-3

#include "stdio.h" 
int main() 
{ 
    int marks[] = { 50, 60, 70, 80 }; 
    int *p = &marks[0]; 
    *p++;
    printf("%d ", *p);
    *p = *p+2;
    printf("%d ", *p);
} 

Output: 60 62
Justification: -Address of marks[0] is stored in pointer p; which is incremented by one, hence prints 60 first. 


*p = *p+2;

Value of *p is 60; 2 is added to value it resulting in 62. Hence final output is 60 62.

Program-4

#include <stdio.h>
int main() 
{ 
    int marks[] = { 50, 60, 70, 80 }; 
    int *p = &marks[0]; 
    *p++;
    printf("%d ", *p);
    *p++;
printf("%d ", *p);
} 

Output: 60 70
Justification: Address of marks[0] is stored in pointer p; this memory address is incremented by one; and points to second element of an array and prints 60. Again is it incremented by one resulting final output as 60 70. 

Program-5

#include <stdio.h> 
int main() 
{ 
    int *ptr; 
    *ptr = 5; 
    printf("%d", *ptr); 
    return 0; 
} 


Output: This will results in run time error. 
Justification: Pointer variable (*ptr) cannot be initialized.

Program-6

#include <stdio.h>
int main() {
    int num[] = {1, 2, 3, 4, 5, 6, 7};
    printf("%d", *(num + 2));
    return 0;

}
 
Output: 3  
Justification: Address of num[0] is stored in pointer (*); which is incremented by two, hence prints value 3, which stored at index number 3 in the num[] array.

Program-7

#include <stdio.h> 
void changeMe(int *ptr) {
    *ptr = *ptr + 20;
}
int main() {
    int a = 10;
    changeMe(&a);
    printf("%d", a);
    return 0; 
} 


Output: 30 
Justification: 
  • int *ptr declares a pointer, and stores the address of an integer variable (a).
  • *ptr accesses the value stored at that memory address.
  • *ptr = *ptr + 20 increases the original variable's value by 20, i.e., 10+30, resulting into 30.


No comments:

Post a Comment