C 在Arduino程序中输出不好

C 在Arduino程序中输出不好,c,arduino,C,Arduino,我对这个Arduino项目有意见 这是我的密码 char *stringsplit(char msg[]) { char *words[4]; char * p; int i = 0; char dauphay[] = ","; p = strtok(msg, dauphay); while(p && i < 4) { words[i] = p; p = strtok(NULL, dauphay);

我对这个Arduino项目有意见 这是我的密码


char *stringsplit(char msg[])
 
{
  char *words[4];
   char * p;
  int i = 0;
   char dauphay[] = ",";
  p = strtok(msg, dauphay);
 while(p && i < 4)
  {
    words[i] = p;
    p = strtok(NULL, dauphay);
    ++i;
  }
  return *words;
}
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  char msg[]="first,Second,third,four";
  char *p1=stringsplit(msg);
for(int i = 0; i < 4; i++)
  {
    Serial.println(p1[i]);
  }
}
void loop() {
  // put your main code here, to run repeatedly:

}

char*stringsplit(char msg[])
{
字符*字[4];
char*p;
int i=0;
char dauphay[]=“,”;
p=strtok(味精,道菲);
而(p&i<4)
{
字[i]=p;
p=strtok(空,道菲);
++一,;
}
返回*个单词;
}
无效设置(){
//将安装代码放在此处,以便运行一次:
序列号开始(115200);
char msg[]=“一、二、三、四”;
char*p1=stringsplit(msg);
对于(int i=0;i<4;i++)
{
序列号println(p1[i]);
}
}
void循环(){
//将主代码放在此处,以便重复运行:
}
我的预期输出是“第一、第二、第三、第四” 但我的实际输出是“F i r s” 如何解决此问题

stringsplit()
中,返回
*单词
。这和

return words[0];
换句话说,返回的指针指向第一个字符串,即
first
。 然后,循环依次打印每个元素(字符)


要解决此问题,必须返回整个数组,即指向
单词的指针。这将更改签名和返回到

char **stringsplit(char msg[])
{
    // ...

    return words;
}
但是这也不行,因为现在
stringsplit
返回一个指向局部变量的指针


有几种方法可以解决这个问题

  • 使
    单词
    静止,例如

    static char *words[4];
    
  • 或者使用动态内存分配

    char **words = malloc(4 * sizeof(char*));
    
  • 或者将单词数组传递到stringsplit中

    char **stringsplit(char msg[], char **words)
    {
        // ...
    }
    
    然后在setup()中

每种方法都有其优缺点。在这个小的Arduino示例中(虽然我不是专家),我更喜欢静态变量,因为它快速简单(有些人会说脏;-),即使最后一个方法是最干净的


看看@Furkan的提示,内联打印似乎是最好的解决方案。这还允许轻松地使用任意数量的子字符串

char *p;
char dauphay[] = ",";
p = strtok(msg, dauphay);
while (p) {
    Serial.println(p);
    p = strtok(NULL, dauphay);
}

非常感谢,你能帮我解决这个问题吗?@nghihoang2207你能试着改变一下情况吗i@Furkan谢谢,但我想将输入(MSG)拆分为许多数组,如单词[1],单词[2]…,因此您的解决方案不能帮助我拆分输入,您有其他解决方案吗?请看这里,我希望它能工作。
char *words[4];
char **p1 = stringsplit(msg, words);
char *p;
char dauphay[] = ",";
p = strtok(msg, dauphay);
while (p) {
    Serial.println(p);
    p = strtok(NULL, dauphay);
}