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++);
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++);
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.
Assuming start is pointer and pos is an integer, it can be easily rewritten to:
b[0] = start[pos++];
Hope this helps you understand.
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.
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);
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