[英]C++ Arduino passing char* to an array of char*
I am having a problem with passing a char*
to an array of char**
on my Teensy. 我在Teensy上将char*
传递给char**
数组时遇到问题。
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*
). 正如您所看到的, fuzzyRulesSingle[j]
(其中fuzzyRulesSingle
是char**
)将由变量temp
( char*
)填充。 As I increment j
, the next address in fuzzyRulesSingle
will be filled by a new temp
. 当我增加j
, fuzzyRulesSingle
的下一个地址将由新的temp
填充。
However, when I print my fuzzyRulesSingle
OUTSIDE the code above, all fuzzyRulesSingle
will be filled with the last value of temp. 但是,当我在上面的代码之外打印我的fuzzyRulesSingle
时,所有fuzzyRulesSingle
都将被temp的最后一个值填充。
Where have I gone wrong? 我哪里出问题了?
You are pointing fuzzyRulesSingle[j]
to the temporary char array temp
. 您将fuzzyRulesSingle[j]
指向临时char数组temp
。 A simple way to fix this is to change the fuzzyRulesSingle[j] = temp;
解决此问题的一种简单方法是更改fuzzyRulesSingle[j] = temp;
to strcpy(fuzzyRulesSingle[j], temp)
and changing the declaration of fuzzzyRulessSingle
to the size required. 更改为strcpy(fuzzyRulesSingle[j], temp)
并将fuzzzyRulessSingle
的声明更改为所需的大小。
OR 要么
you can declare temp
outsize the loop and use malloc
to allocate memory necessary and then assign it to fuzzyRulesSingle[j]
您可以声明temp
超出循环大小,并使用malloc
分配必要的内存,然后将其分配给fuzzyRulesSingle[j]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.