Array auto changed

I'm using RS485 to connect between arduino mega2560 and UHF, but once I read the callback hex value and store them in the array, It's auto changed.

  uint8_t buf[5] = {0x04,0x00,0x01,0xDB,0x4B};
  UHF.write(buf,5);
  uint8_t res[] = {};

  int i = 0;
  while(UHF.available()){
      res[i] = UHF.read();
      // Serial.print(c);
      Serial.print(res[i++],DEC);
      Serial.print(" ");
  }

  Serial.print('\n');
  for(int j=0; j<11;j++){
    Serial.print(res[j],DEC);
    Serial.print(" ");
  }
  Serial.print('\n');
  Serial.print('\n');

How many array elements?

What makes you think that this is an installation or troubleshooting issue?

now it's about 12, but could be more than 1000, sorry for putting it in the wrong place, I've already changed it.

No, now it's about zero elements

I get it, thank you; but what if I don't know how long it would be. How should I initialize the array?

To the maximum number of elements You intend to use.

I've solved it out:

uint8_t* res = (uint8_t*)malloc(sizeof(uint8_t));

two options:

  • 1/ make a decision on the largest array you expect and reserve the memory by making a global array with that size. In the code make sure you never write beyond the bounds of the array and decide what to do in case this happens.

  • 2/ handle an unknown size and be ready to deal with issues of reallocating memory dynamically. This comes with possible challenges like poking holes in the heap.

option 1 is the easier route

where do you free this ?

after generating the hex value

you allocated only 1 byte.... won't be able to store much

I know, I just put a sample code, thx though

just do

const size_t maxSize = 1000;  
uint8_t res[maxSize];
size_t currentPos = 0;

while(UHF.available()){
     uint8_t r =  UHF.read();
     if (currentPos < maxSize ) res[currentPos++] =  r;
 }
// here you know you have currentPos elements
...

of course you need 1000 bytes freely available....

You 've gone from zero elements to one element

on the bright side it only leaks 1byte

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.