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

I am trying to learn C while playing with Arduino Uno. I am looking at the code for the Colorduino library on github . I am wondering how ++ works when applied to a structure.

There is a PixelRGB structure defined in Colorduino.h :

 typedef struct pixelRGB { unsigned char r; unsigned char g; unsigned char b; } PixelRGB; 

Colorduino.cpp has a bit of code that applies the ++ operator to the PixelRGB pointer. How it works?

 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++; } } 
+4
source share
2 answers

Note that this code increments the pointer to PixelRGB , not the structure. Thus, the result of ++ when applied to a pointer simply increases its value by sizeof(PixelRGB)

+9
source

p is a pointer, not a structure, so it works like pointer arithmetic on any type. The pointer value is the address. Therefore, when, for example, you add n to the pointer, it changes the value and points to the new address n * sizeof type . So that...

 char *p = malloc(SOME_NUMBER * sizeof char); p++; // p = p + sizeof char p += 4; // p = p + sizeof char * 4 

And if you have a structure ...

 typedef struct { int a; } foo; /* ... */ foo *fp = malloc(SOME_NUMBER * sizeof foo); fp++; // fp = fp + sizeof foo; fp += 4; // fp = fp + sizeof foo * 4; 
+5
source

All Articles