Reputation: 63
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?
Upvotes: 0
Views: 372
Reputation: 28950
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
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.
Upvotes: 1