Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference Between (void *)pointer and &pointer?

I'm learning C using LCTHW and I came across some pointer stuff that interested me, so I found this. While going through it, I found this code:

void *vptr; // declare as a void pointer type
int val = 1;
int *iptr;

// void type can hold any pointer type or reference
iptr = &val;
vptr = iptr;
printf("iptr=%p, vptr=%p\n", (void *)iptr, (void *)vptr);

Running that gives me something like this:

iptr=0x7fffa97a8464, vptr=0x7fffa97a8464

Obviously, the memory addresses would be the same, so C prints out the same thing for both of them. However, when experimenting with the code and putting in, instead of the last line:

printf("iptr=%p, vptr=%p\n", &iptr, &vptr);

I get this:

iptr=0x7fff61a21ee0, vptr=0x7fff61a21ed8

I get two different memory addresses printed out, which shouldn't be happening. First question: If the ampersand here means "address of," as Dennis says in the post, then why do the two lines of code output two different things? Second question: Since the two lines of code output two different things, obviously (void *)pointer must mean something different than &pointer. What is the difference between those two things?

like image 768
slinky773 Avatar asked Mar 24 '26 05:03

slinky773


2 Answers

(void*)ptr casts ptr to a void pointer without altering its value. &ptr, on the other hand, yields the address of the pointer itself. In other words, &ptr is a pointer to a pointer. iptr and vptr are different objects and as such they have different addresses.

(void *)pointer casts pointer to a pointer-to-void—that is, a pointer to anything. &pointer, on the other hand, takes the address of the variable (not that to which it points), so if pointer was of type char *, the type of &pointer would be char **. The reason this:

printf("iptr=%p, vptr=%p\n", &iptr, &vptr);

prints two different values is because though iptr and vptr contain the same value (they point to the same thing), they are two different variables, and so the variables themselves are distinct.

like image 26
icktoofay Avatar answered Mar 27 '26 10:03

icktoofay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!