简体   繁体   中英

C Programming- Pointers

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);
}

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);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM