0

So in my arduino programm I am working with char arrays in a function. I try to save them globally, but no matter how I do it, the global arrays contain only part of the original array and a ton of gibberish symbols.

char* naam;
char* compliment;
byte color = 0;

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  
  doStuff();
  
  Serial.println(naam);
  Serial.println(compliment);
  Serial.println(color);
  
}

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

}

void doStuff(){
  String raw = "1234567890123456,abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz,0";
  int i = raw.indexOf(",");
  int j = raw.indexOf(",", i+1);
  char a[i+1];
  char b[j-i];
  
  raw.substring(0,i).toCharArray(naam, i+1);
  raw.substring(i+1,j).toCharArray(compliment, j);
  color = (byte) raw.substring(j+2,j+3).toInt();
  Serial.println(a);
  Serial.println(b);

  naam = a;
  compliment = b;
}

Can anyone explain to me why this does not work and point me in the right direction?

STEENBRINK
  • 53
  • 7
  • 1
    next time please add a few comments to your code so we can follow your thought process. – Piglet Mar 16 '21 at 10:08
  • First, `naam` and `compliment` are not arrays, they are just pointers to some *undefined* memory location. Second, as @Piglet answered,`a` and `b` are uninitialized data on the stack. Third, `a` and `b` will be trashed by other stack use once `doStuff` returns. At that point, `naam` will remain pointing to garbage on the stack. Fourth, the first time around `naam` is unset, so where exactly is `toCharArray(naam, i+1)` putting the characters? Somewhere, you need to actually allocate storage outside of the stack, and do tests to make sure your detected strings can actually fit in that storage. – aMike Mar 16 '21 at 13:03

1 Answers1

1

Here you create two char arrays a and b

char a[i+1];
char b[j-i];

You never assign any values to its elements befor you print them.

Hence you'll print whatever garbage is in those memory locations

Response to comment:

They are filled by the "toCharArray(compliment, j);". The println(a) prints correctly

When you first call doStuff

You create two uninitialized char arrays a and b. Then you store two substrings as char array to naam and compliment. Both uninitialized char pointers. So you're basically storing stuff in a random position in memory.

Then you print a and b which contain random garbage.

Then you store the addresses in a and b to naam and compliment.

Once doStuff returns a and b are out of scope. naam and compliment still point at their position but that memory is free to be used by something else.

Piglet
  • 27,501
  • 3
  • 20
  • 43