C Programming - Pointers - Discussion

Discussion Forum : Pointers - Find Output of Program (Q.No. 6)
6.
What will be the output of the program ?
#include<stdio.h>

void fun(void *p);
int i;

int main()
{
    void *vptr;
    vptr = &i;
    fun(vptr);
    return 0;
}
void fun(void *p)
{
    int **q;
    q = (int**)&p;
    printf("%d\n", **q);
}
Error: cannot convert from void** to int**
Garbage value
0
No output
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
95 comments Page 7 of 10.

Shambhu said:   1 decade ago
In this program i is declared as a global variable. And we know that global variable initially initialized to be 0.

So int i=0;

Now void pointer(it is a pointer which points any data type)pointing to the base address of int i.

So it point the base address of i(means 0).

1st step:

vptr contain the address of i, so it contain 0.
and passes it through function.

2nd step:

In fun....
We assign the value contain in *p in q.
So dereference it we get the value present in i.
i.e----> 0.

Rachit said:   1 decade ago
Please tell me the significance of (int**) because if we write (int) or (int****...) then also the answer is same.

Anu said:   1 decade ago
void *vptr;

Is it correct?

Raj Naik said:   1 decade ago
@Anu : yeah..void *vptr is valid.

A void pointer is pointer which has no specified data type and the void pointer can be pointed to any type. If needed, the type can be casted as : int **q =(int **)&vptr.

Akshay K said:   1 decade ago
In given code, vptr is a void pointer and 'i' is integer variable.
But vptr assigned the address of integer variable without typecasting.

see code:
---------------
int main()
{
void *vptr;
vptr = &i;
--------------

So, it takes value as 0.

Indira said:   1 decade ago
Can anyone tell me?

q = (int**)&p = q = (int)&p.

What is the use of (int**).

Shruthi said:   1 decade ago
Whether *(int*) is same as (int**)?

Vicky said:   1 decade ago
Since it has the type void it is called as null pointer. Which is general purpose pointer. Instead of declaring pointer as int, float, char as 3 times.

We can use null pointer. Which stores address of any datatype for eg: int, float.

Because it does not have any type, compiler does not know what datatype pointer is holding. For that we have to do typecast.

int main()
{
int inum = 8;
float fnum = 67.7;
void *ptr;
ptr = &inum;
printf("\nThe value of inum = %d",*((int*)ptr));//tells compiler that ptr is holding integer value and returns 8
ptr = &fnum;
printf("\nThe value of fnum = %f",*((float*)ptr));//tells compiler that ptr is holding float value and returns 67.7
return(0);
}

Mohamed mohsen said:   1 decade ago
Because i is global variable by default compiler initialize it to zero.

Prasun said:   1 decade ago
By default the global variable has default value 0. So answer is 0.


Post your comments here:

Your comments will be displayed after verification.