Reputation: 1
I'm working on updating a code of a server project since days. I found a line that I cannot understand (which was commented)
First, I get :
int *t;
Then I got this (commented):
t[*t];
What's the type of this "t[*t]"
Upvotes: 0
Views: 399
Reputation: 11
The operator[]
of int*
always returns an int
.
Since *t
simply returns the first element of t
, t[*t]
is the element of t
pointed to by the first element of t
.
Example:
int *t;
t=new int[5];
for(int i=0;i<5;++i){
t[i]=i+1;
} // t now points to {1,2,3,4,5}
t[*t]; // <--- What does this evaluate to?
In this case t[*t]
will be 2.
Because *t
is 1, t[1]
is the second element in the array, which is 2.
Upvotes: 0
Reputation: 311088
Sometimes code is estimated by the number of typed symbols. So I would write a more confusing code but with more characters like:)
( t + *t )[*t];
Relative to your example
*t
is some integer stored in t
that is *t
is equivalent to t[0]
. Thus in expression t[*t]
there is used the pointer arithmetic
t + *t
or
t + t[0]
that gives some new pointer that then is dereferenced
*( t + *t )
Upvotes: 0
Reputation: 19731
By definition of the language, given that t
is a pointer, the expression t[*t]
is completely equivalent to the expression *(t + *t)
.
To analyze the type of that expression, let's look at it step for step, from the inside out. I'll replace each expression whole type was identified with «type»
.
Since t
is of type int*
, we have *(«int*» + *«int*»)
.
Dereferencing an int*
gives an lvalue of type int
. Therefore we get *(«int*» + «int»)
.
Now adding an integer to a pointer gives, again, a pointer of the same type, so the expression reduces to *«int*»
.
But that is, again, just the dereferencing of a pointer to int
, and therefore the final type of the expression is lvalue int
.
Upvotes: 0
Reputation: 1051
The type is int
*t
is equivalent to t[0]
as such your expression is equivalent to the follow:
t[*t] == t[t[0]] == t[offset]
(if you consider offset = t[0]
)
Upvotes: 1
Reputation: 303537
The type is an int
lvalue. We have two parts:
*t // this is an int
t[ some int ] // this is standard array indexing
Or for a simple example:
int array[] = {1, 2, 3, 4};
int* t = array;
With that setup:
t[*t] == t[1] == 2
Or:
t[*t] = 7;
// now array[] holds {1, 7, 3, 4}
Upvotes: 2