I'm having a problem trying to fill an array with a positive number (not zero), and I'm pretty sure I'm not doing something right, but it escapes me right now. Can someone maybe point out the obvious that I am missing?
Here's some minimum code that duplicates my problem.
uint16_t* myvariable;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
myvariable = (uint16_t*) calloc(21, sizeof(uint16_t));
setmyvariable();
printmyvariable();
}
void setmyvariable() {
memset(&myvariable[0], 4095, 21*sizeof(uint16_t));
}
void printmyvariable() {
Serial.println("myvariable data:");
for (int i = 0; i < 21; i++) {
Serial.print("Slot ");Serial.print(i);Serial.print(": ");Serial.println(myvariable[i]);
}
}
void loop() {
// put your main code here, to run repeatedly:
}
The array ends up getting filled with 65535 instead of 4095. What am I doing wrong? Or, is there a better way to do this? I'm using memset because sometimes I don't start at the first position (0). Sometimes I need to start in the middle setting more than one by changing it to something like this.
The second parameter to memset (your 4095 value) is interpreted as an unsigned character (byte). 4095 is 0x0FFF hex. So you end up setting each byte in the array to 0xFF. Each uint16_t is 2 bytes. And 0xFFFF is 65535.
I found this example that someone posted to make a memset16 function that they say works, but it doesn't seem to work for me.
void *memset16(void *m, uint16_t val, size_t count)
{
uint16_t *buf = m;
while(count--) *buf++ = val;
return m;
}
The error I get is:
invalid conversion from 'void*' to 'uint16_t*' {aka 'short unsigned int*'} [-fpermissive]
Any thoughts? If if helps, I'm working with an ESP32. Also, I'm using the exact same line as before to call it (except with memset16 instead of memset) just for testing.
I realize that functionally it is the same. It was more of "i found this and it's not working, so I'm curious why." It helped me learn something.
I could have gone with a loop and it would be more readable, but sometimes I like to just have less lines of code to look at too. I know, I like to be difficult. LOL
Honestly, I was all set to use a loop instead, until I scrolled upon a post that had a bunch of different options to try and I just figured it would be another learning experience.
I guess I never really thought about casting the void * to uint16_t * because I haven't written (or used from anyone else to my knowledge) a function that passed anything as a void like that. As suggested, that fixed the problem. This is all new to me and I appreciate the help.