I have defined a byte array as a constant in the Atmel's flash memory:
const uint8_t eye [] PROGMEM = {
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff
};
How can I (repeatedly) read the length of this constant in the program? All the available functions in avr/pgmspace.h do not deliver the proper length, no matter how I use them. I tried strlen(eye), strlen_P(eye), strLen_PF(eye) and also sizeof(eye). I'm new to C, so I'm not sure about the whole pointer stuff.
1 Answer 1
Probably the best way would be to define below it
const int eye_len = sizeof(eye)/sizeof(eye[0]);
If the linker does link time optimization, or if you only use it within the same file (and declare it static), it shouldn’t cost any memory, otherwise it will take up two bytes of ram.
-
That works, although I don't know how. Guess I have to read more about C.needfulthing– needfulthing2018年04月02日 19:19:17 +00:00Commented Apr 2, 2018 at 19:19
-
Sizeof(array) gives the size of the entire array in bytes, and sizeof(array[0]) gives the size in bytes of one element in the array. Divide the first by the second and you get the number of items in your array. In this case you could do without the second sizeof, but it makes it still work even if you change the data type in the array.C_Elegans– C_Elegans2018年04月02日 19:27:05 +00:00Commented Apr 2, 2018 at 19:27
-
@needfulthing all of the strlen stuff wouldnt work because this isnt a string (which needs to be null terminated). The sizeof returns the size of the array in bytes, so if you want to know the number of items in the array, you take the size in bytes and divide that by the number of bytes that each item takes up. In this case though, uint8_t is 1 byte, so just sizeof(eye) should also have worked on its own, and it's odd that it didnt originally work for you.BeB00– BeB002018年04月02日 19:29:23 +00:00Commented Apr 2, 2018 at 19:29
-
@BeB00 could be that he used sizeof(eye) in another file, and it gave him the size of a pointerC_Elegans– C_Elegans2018年04月02日 19:30:59 +00:00Commented Apr 2, 2018 at 19:30
-
That totally sounds logic. I confused a lot of things by using length functions for strings on a byte array (which counted on because of missing null termination) and receiving the pointer length instead of the array length. That's what you get when making yourself too comfortable in high-level languages... :)needfulthing– needfulthing2018年04月03日 11:39:25 +00:00Commented Apr 3, 2018 at 11:39
sizeof()
, when provided with a pointer to a const (or a pointer to anything else for that matter), which is what you have when you pass it to a function, gives you the size of that pointer. On an 8-bit Arduino that will always be 2.strlen()
only works on strings - null-terminated arrays, which that isn't.