Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are these two methods for setting pointers equal to each other the same?

Tags:

c

pointers

I am curious, if I have two pointers

int *x = (int *)malloc(sizeof(int));
int *y;

and I want y to point to the address of x, is

y = x;

the same as

y = &*x;

?

like image 635
user1876508 Avatar asked Nov 30 '22 03:11

user1876508


2 Answers

Your question has two parts, and it's worth noting that they are not both correct:

First, you ask:

is
y = x;
the same as
y = &*x;

Since the dereference (*) and address-of (&) operators have the same precedence they will bind right to left, so

y = &*x;

is the same as:

y = &(*x);

And yes, that will yield the same effect as y=x; Now if you have a C compliant compiler that follows the letter of the law, it will not only be the same effectively, it will be the same, this is due to section 6.5.3.2 P3 of the C Specification:

The unary & operator yields the address of its operand. If the operand has type ‘‘type’’, the result has type ‘‘pointer to type’’.

If the operand is the result of a unary * operator, neither that operator nor the & operator is evaluated and the result is as if both were omitted

So the compiler will see both the * and & together and omit them entirely.


In the second half of your question you stated:

I want y to point to the address of x

Presumably you know that that's not what you're doing, but you're setting y to point to the same address as x instead. x of course has its own address and that could be set, but you'd need a different variable int **y = &x; assuming x is a valid value to be dereferenced.

like image 94
Mike Avatar answered Dec 05 '22 06:12

Mike


They are functionally equivalent. This is effectively a "shallow copy".

So, the following assignments achieve the same final result:

y=x;

y=&(*x);

However, the second operation will take more time to execute because rather than just a direct assignment, you are performing an indirection then an address-of operation. The compiler may just optimize this down to y=x anyways, depending on your system.

Edit:


As the poster below notes, if your compiler supports the C standard, including 6.5.3.2 P3 of the C standard, this will definitely be optimized out, likely at the pre-processor level before the code is even compiled.

like image 30
Cloud Avatar answered Dec 05 '22 07:12

Cloud