38. Add Two Integers Using Void Pointers

#include <stdio.h>

// Function to add two integers via void pointers
int add_two_void_pointers(void *a, void *b) {
    int *ptr1 = (int *)a;  // Cast to int pointer
    int *ptr2 = (int *)b;  // Cast to int pointer
    return *ptr1 + *ptr2;  // Dereference and return sum
}

int main() {
    int x, y;
    scanf("%d %d", &x, &y);

    int result = add_two_void_pointers(&x, &y);
    printf("%d", result);

    return 0;
}
  • void * cannot be directly dereferenced.
  • Must be typecast to (int *) first.
  • After casting, dereference both and return their sum.

 

Loading...

Input

10 20

Expected Output

30