121k views
1 vote
What is the output of the following code?

1) int value provided
2) float value provided
3) Invalid type provided
4) Value of x: 600


void process(void *dataPtr, int type) {
int a;
double b;

if (type == 1) {
a = *((int *)dataPtr);
printf(""int value provided %d\\"", a);
} else if (type == 2) {
b = *((float *)dataPtr);
printf(""float value provided %f\\"", b);
} else {
printf(""Invalid type provided\\"");
}
}

int main() {
int x = 200;
float y = 4.4;
int *xPtr;
void *vPtr;

/* You can assign any address to a void pointer */
vPtr = &y; /* assigning pointer to float */
vPtr = &x; /* assigning pointer to int */

/* We cannot dereference void ptr */
/* *vPtr = 100; */

*((int *)vPtr) = 400;
printf(""Value of x: %d\\"", x);

xPtr = (int *)vPtr;
*xPtr = 600;
printf(""Value of x: %d\\"", x);

/* Void pointers allow us to pass any data */
process(&x, 1);
process(&y, 2);

return 0;
}"

1 Answer

3 votes

Final answer:

The output of the code will be the value of x changed to 400 and then 600, followed by the values from process function.

Step-by-step explanation:

The output of the code will be:

  1. Value of x: 400
  2. Value of x: 600
  3. int value provided 600
  4. float value provided 4.400000

In this code, a void pointer (vPtr) is used to store the addresses of both an int and a float variable. By casting the void pointer to the appropriate type and dereferencing it, we can retrieve the value stored at that address. The process function takes a void pointer and an integer type as arguments and uses casting to correctly retrieve and print the value of the passed variable based on its type.

User Ccordon
by
8.3k points