0

I am having a problem with passing a char* to an array of char** on my Teensy.

Below is the problematic part:

for (j = 0; j < rulesamountsingle; j++) {
   emptybuffer(buff);
   char temp[10];
   while(!Serial.available());
   len = Serial.available();
   for (i = 0; i < len; i++) {
     temp[i] = Serial.read();
   }
   temp[len-1] = 0;
   fuzzyRulesSingle[j] = temp;
   Serial.print(fuzzyRulesSingle[j]);
   Serial.print('\n');
 }

As you can see, fuzzyRulesSingle[j] (where fuzzyRulesSingle is a char**) will be filled by the variable temp (a char*). As I increment j, the next address in fuzzyRulesSingle will be filled by a new temp.

However, when I print my fuzzyRulesSingle OUTSIDE the code above, all fuzzyRulesSingle will be filled with the last value of temp.

Where have I gone wrong?

Maksim Solovjov
  • 3,147
  • 18
  • 28
Keni Mardira
  • 25
  • 1
  • 3
  • 1
    You reuse `temp` over and over so `fuzzyRulesSingle[j]` always points to the same place. You need to copy the chars in `temp` into `fuzzyRulesSingle[j]` - allocating space first. – 001 Sep 16 '15 at 13:16
  • Can you show us the definition of fuzzyRulesSingle object. Is it an array of pointers or arrays? – rozina Sep 16 '15 at 13:39

1 Answers1

1

You are pointing fuzzyRulesSingle[j] to the temporary char array temp. A simple way to fix this is to change the fuzzyRulesSingle[j] = temp; to strcpy(fuzzyRulesSingle[j], temp) and changing the declaration of fuzzzyRulessSingle to the size required.

OR

you can declare temp outsize the loop and use malloc to allocate memory necessary and then assign it to fuzzyRulesSingle[j]

Eric Finn
  • 8,629
  • 3
  • 33
  • 42
kist
  • 590
  • 2
  • 8