sizeof() char array

After some wrangling, this little bit of code compiles but gives a curious result. The size reported for char* posnText[] is 12. Why not 6, or 48 or 17? Is it because pointers are two bytes?

char* posnText[] = {"topline1",
                          "topline2",
                          "topline3",
                          "topline4",
                          "topline5",
                          "topline6"
                         };
struct menuItems {
  char* topLineText;
  char* bottomLineText;
  byte numOfParms;
};
menuItems screenText[2] = {
  "top1", "bottom1", 4,
  "top2", "bottom2", sizeof(posnText)/2,
};


void setup() { 
Serial.begin(9600);
Serial.println (screenText[1].bottomLineText);
Serial.print("size ");
Serial.println(sizeof(posnText));
}

void loop() {
  // put your main code here, to run repeatedly:

}
1 Like

Is it because pointers are two bytes?

It is because pointers are the same size as ints, and ints are two bytes on some Arduinos.

Aah. Thanks!

Each element posnText is a pointer to a char. The size of a pointer is indeed 2 bytes on most 8-bit Arduinos, and there are 6 elements in the array, so the total size will be 12 bytes.
To get the number of strings in posnText, use:

const size_t nb_strings = sizeof(posnText) / sizeof(posnText[0]);

posnText[0] is a pointer, so sizeof(posnText[0]) will return 2.

Each of the six char pointers points to a string of characters in static memory. To get the number of characters in one of these strings, you can use the strlen function.

Pieter

You can expand PieterP's concept to:

#define ELEMENTS(x) (sizeof(x) / sizeof(x[0]))

which allows you to do things like:

   for (int i = 0; i < ELEMENTS(posnText); i++) {
      // rest of code

The advantage of the macro over Pieter's version is that the macro is "typeless"; you can use it with any array.

And, have no fear, the calculation is done at compile time, so there is little to no performance penalty due to the division.

Good stuff! Thread bookmarked.