I'm trying to learn C by playing with an Arduino Uno. I'm reviewing the code for the Colorduino library on github. I'm wondering how ++
works when applied to a struct.
There is a PixelRGB
struct defined in Colorduino.h:
typedef struct pixelRGB {
unsigned char r;
unsigned char g;
unsigned char b;
} PixelRGB;
In Colorduino.cpp there is a bit of code that applies the ++
operator to a PixelRGB
pointer. How does this work?
for (unsigned char y=0;y<ColorduinoScreenWidth;y++) {
for(unsigned char x=0;x<ColorduinoScreenHeight;x++) {
p->r = R;
p->g = G;
p->b = B;
p++;
}
}
Note, that this code increments pointer to PixelRGB
, not the struct itself.
So, the result of ++
when applied to pointer, is just incrementing its value by sizeof(PixelRGB)
p
is a pointer, not a struct, so it works like pointer arithmetic does on any type. The pointer's value is an address. So when, for example, you add n
to a pointer, it's value changes and points to a new address n * sizeof type
away. So...
char *p = malloc(SOME_NUMBER * sizeof char);
p++; // p = p + sizeof char
p += 4; // p = p + sizeof char * 4
And if you have a struct...
typedef struct {
int a;
} foo;
/* ... */
foo *fp = malloc(SOME_NUMBER * sizeof foo);
fp++; // fp = fp + sizeof foo;
fp += 4; // fp = fp + sizeof foo * 4;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With