struct MyStruct
{
const char name[15];
const uint8_t code;
const float resolution;
};
MyStruct listInfo[] =
{
{"sen0", 0x01, 1.0}, //0
{"sen1C", 0xff, 0.01}, //1
{"sen2", 0xcf, 0.01},
{"sen3", 0xaa, 0.01},
};
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32-S2!");
}
void loop() {
int size = getStrucSize(listInfo);
Serial.print("size:");
Serial.println(size);
delay(500);
}
int getStrucSize(MyStruct * structure)
{
size_t i ,j ;
i = sizeof(structure);
Serial.println("****");
Serial.println(i); //return the size of pointer instead of 80
j = sizeof(structure[0]);
Serial.println(j); //return 20 and is OK
Serial.println("****");
return i/j;
}
inside getStrucSize, i never get get the right value.
I try to use
i = sizeof(*structure); //but i got the same issue.
getStrucSize(&listInfo); // this one fails to compile with an type conversion error that i do not quite understand
I finally change the getStrucSize function by passing as and arg the size of the struct array (
int getStrucSize(MyStruct * structure, int sizeOfStruct) ). And it seems this approach is "safer"
But for my knowledge, can someone point the error out ?
When you pass an array to a function what is actually passed is a pointer to the array. The pointer will be an int so what sizeof() returns is the size of an int, not the size of the array
That is the classic way of finding the number of elements in an array but won't work when you do the calculation in a function to which the array has been passed as a parameter because what is passed is a pointer to the array rather than the array itself
I was answering in the context of the original question where one uses the C-style method of passing an array to a function. In that case, the array's name decays to a pointer. So once inside the function, sizeof(pointer) will give the size of a pointer on the platform in question and sizeof(*pointer) will give the size of a single object in the array being pointed to . However nothing will give you the number of elements in the array. Again, this is inside the function.
in another thread someone asked about returning a ptr to a (locally) defined array and knowing it's size.
besides that fact the the local array is allocated on the stack i said it's common for the calling function to pass an array along with its size to the function which then populates it, possibly returning the # of elements populated