Pages

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.


No comments:

Post a Comment