问题
I am trying to understand a line of C-code which includes using a pointer to struct value (which is a pointer to something as well).
Example C-code:
// Given
typedef struct {
uint8 *output
uint32 bottom
} myType;
myType *e;
// Then at some point:
*e->output++ = (uint8) (e->bottom >> 24);
Source: http://tools.ietf.org/html/rfc6386#page-22
My question is:
- What exactly does that line of C-code do?
回答1:
"What exactly does that line of C-code do?"
Waste a lot of time having to carefully read it instead just knowing at a glance. If I was doing code review of that, I'd throw it back to the author and say break it up into two lines.
The two things it does is save something at e->output, then advance e->output to the next byte. I think if you need to describe code with two pieces though, it should be on two lines with two separate statements.
回答2:
As pointed out by Deduplicator in the comments above, looking at an operator precedence table might help.
*e->output++ = ...means "assign value...to the locatione->outputis pointing to, and lete->outputpoint to a new location 8 bits further afterwards (becauseoutputis of typeuint8).(uint8) (e->bottom >> 24)is then evaluated to get a value for...
回答3:
The line
*e->output++ = (uint8) (e->bottom >> 24);
does the following:
- Find the field
bottomof the structure pointed to by the pointere. - Fetch the 32-bit value from that field.
- Shift that value right 24 bits.
- Re-interpret that value as a
uint8_t, which now contains the high order byte. - Find the field
outputof the structure. It's a pointer touint8_t. - Store the
uint8_twe computed earlier into the address pointed to byoutput. - And finally, add 1 to
output, causing it to point to the nextuint8_t.
The order of some of those things might be rearranged a bit as long as the result behaves as if they had been done in that order. Operator precedence is a completely separate question from order in which operations are performed, and not really relevant here.
来源:https://stackoverflow.com/questions/27281887/c-operator-precedence-with-pointer-increments