62. void pointer and Casting

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>

void add_and_print(void *a, void *b, char type) {
    // Type casting
    // 1. To type cast to a void, create a new pointer of the correct type and type cast the void pointer
    if (type == 'i'){
        int *int_a_ptr = (int *) a; //Casting void a and b to int pointers
        int *int_b_ptr = (int *) b;
        //ALTERNATE METHOD 
        //int result = value of the item at a which has been typecasted as a int pointer
        //(int result = *(int *)a + *(int *)b)
        int result = *(int_a_ptr) + *(int_b_ptr); //Result = value at intptra + value at intptrb
        printf("%d\n", result);        
    }
    else if(type == 'f'){
        float *flt_a_ptr = (float *) a; //Casting void a and b to int pointers
        float *flt_b_ptr = (float *) b;
        float result_flt = *(flt_a_ptr) + *(flt_b_ptr); //Result = value at intptra + value at intptrb
        printf("%.1f\n", result_flt); //Float to 1dp
    }
}

int main() {
    char type;
    scanf(" %c", &type);

    if (type == 'i') {
        int x, y;
        scanf("%d %d", &x, &y);
        add_and_print(&x, &y, type);
    } else if (type == 'f') {
        float x, y;
        scanf("%f %f", &x, &y);
        add_and_print(&x, &y, type);
    }

    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote