Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the behavior of the plus plus (++) operator when applied to a struct?

Tags:

c

struct

arduino

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++;
  }
}
like image 728
Eric Schoonover Avatar asked Dec 08 '22 21:12

Eric Schoonover


2 Answers

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)

like image 190
Alexander Putilin Avatar answered May 04 '23 01:05

Alexander Putilin


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;
like image 34
Ed S. Avatar answered May 04 '23 01:05

Ed S.