bigben
bigben

Reputation: 15

C * operator meaning in array assignment

What does this line mean? I havn't done C in a few years. Does it perform the operation in parens then make the int result a pointer??

b[0] = *(start + pos++);

Upvotes: 1

Views: 670

Answers (5)

seh
seh

Reputation: 15269

Note the equivalence of these expressions. First, assume the following declarations establish the types in play:

T* const base;
size_t const pos;

Now, an object of type T located in memory at position

base + sizeof(T) * pos

can be accessed in several ways:

base[pos]                            // Interpret base as an array.
*(base + pos)                        // Pointer arithmetic strides by sizeof(T)
*(T*)((char*)base + sizeof(T) * pos) // Compute stride manually

Upvotes: 1

Thomas Matthews
Thomas Matthews

Reputation: 57749

The operator '*' returns the value at the location pointed to by the pointer or expression following the operator.

Some examples:

value = *pointer;
value = *(pointer);     // Exactly the same as the first statement.
value = *(pointer + 0); // Take contents of pointer and add zero then dereference.
value = *(pointer + 1); // Deference the first location after the location in pointer.

Sometimes, especially in embedded systems, this is more readable than using the array notation. Example: status = *(UART + STATUS_REGISTER_OFFSET);

Upvotes: 2

Christoph
Christoph

Reputation: 169833

For this to make sense, either start or pos must be a pointer; most likely, it will be start. The code can then be written as

b[0] = start[pos];
pos = pos + 1;

Actually, the code is equivalent even if pos were the pointer because of C's somewhat funny semantics of array subscription.

Upvotes: 3

Frunsi
Frunsi

Reputation: 7157

Assuming start is pointer and pos is an integer, it can be easily rewritten to:

b[0] = start[pos++];

Hope this helps you understand.

Upvotes: 5

AnT stands with Russia
AnT stands with Russia

Reputation: 320797

Apparently start is a pointer (or an array, which will decay to a pointer here anyway), which means that the result of the expression in () is a pointer, not an int. The * simply dereferences that pointer.

The whole thing is equivalent to plain b[0] = start[pos++], but for some reason some people prefer to use the obfuscated form as in your post.

Upvotes: 8

Related Questions