-1

I came across the following code, the output for which is 0.

Is the statement vptr = &i correct? Can we assign a void pointer, address of an integer variable?

#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);
}
3
  • Define "correct". Syntax? Semantics? Usage? Behavior? Practice? Commented Sep 9, 2016 at 17:29
  • A void pointer can be assigned a memory address of anything. It is sometimes used in C to program "generics" Commented Sep 9, 2016 at 17:29
  • @SouravGhosh correct means its behaviour, can we assign an integer type memory to void using the above statement? Commented Sep 10, 2016 at 18:42

2 Answers 2

8

The statement vptr = &i; is fine.

However, the statement q = (int**)&p; is incorrect. &p does not point at an int*, it points at a void*. It is not guaranteed that int* and void* have compatible layouts.

A correct implementation of fun would be

void fun(void *p)
{
    printf("%d\n", *(int*)p);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Any pointer type can be converted into void*. From the C standard 6.3.2.3p1:

A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.