Q24 Write a program to implement generic pointer.

Admin

Write a program to implement generic pointer.

#include <stdio.h>
#define SIZE 10
void printArray(void * vPtr, int size, int type);
int main()
{
    int num[SIZE] = {10, 20, 30, 40, 50, 60,70, 80, 90, 100};
    float fractional[SIZE] = {1.1f, 1.2f, 1.3f,1.4f, 1.5f, 1.6f, 1.7f, 1.8f, 1.9f, 2.0f};
    char characters[SIZE] = {'C', 'o', 'd', 'e','f', 'o', 'r', 'w', 'i', 'n'};

    printf("\nElements of integer array: ");
    printArray(&num, SIZE, 1);

    printf("\nElements of float array: ");
    printArray(&fractional, SIZE, 2);

    printf("\nElements of character array: ");
    printArray(&characters, SIZE, 3);
    return 0;
}
void printArray(void * vPtr, int size, int type)
{
    int i; 
    for(i=0; i<size; i++)
    {
        switch(type)
        {
            case 1: 
                printf("%d, ", *((int *)vPtr + i));
            break;
            case 2: 
                printf("%.2f, ", *((float *)vPtr + i));
            break;
            case 3: 
                printf("%c, ", *((char *)vPtr + i));
            break;
        }
    }
}

Output

Elements of integer array: 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 
Elements of float array: 1.10, 1.20, 1.30, 1.40, 1.50, 1.60, 1.70, 1.80, 1.90, 2.00, 
Elements of character array: C, o, d, e, f, o, r, w, i, n, 

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.