使用解除引用运算符分配导致无限循环

时间:2015-12-17 06:03:22

标签: c++ arrays csv pointers strtok

我正在尝试使用strtok()函数将字符数组解析为指针数组。我初始化我的字符数组和指针数组:

char micPointsChar[30 + 1] = {};
float* micPoints[8][8] = {};
void initMicPoints(char* micPointsChar);

我调用函数initMicPoints()并将字符数组micPointsChar[40]传递给它:

int main()
{
  char micPointsChar[40] = "1,1.546466,2.543\n2,3.343,4.432\n";
  initMicPoints(micPointsChar);
  return 0;
}

然后我遍历.csv文件中的每一行,通过使用分隔符",#34;来提取每个单元格中的数据。和" \ n"。

void initMicPoints(char* micPointsChar)
{
  static int i = 1;
  static int micNum = 1;
  static int numMics = 2;
  static float coordinateDec = 0;

  char *coordinate = strtok(micPointsChar, ",\n");
  coordinateDec = atof(coordinate);
  while (micNum <= numMics)
  {
    Serial.print("looping number of mics\n");  //debugging
    while (i <= ((micNum * 3)) && (coordinate != NULL))
    {
      if (i == ((micNum * 3) - 2))
      {
        *micPoints[micNum][0] = coordinateDec;
        Serial.print("*micPoints[micNum][0] = "); //debugging
        Serial.print(*micPoints[micNum][0]);
        Serial.print("\n");
      }
      else if (i == ((micNum * 3) - 1))
      {
        *micPoints[micNum][1] = coordinateDec;
        Serial.print("*micPoints[micNum][1] = "); //debugging
        Serial.print(*micPoints[micNum][1]);
        Serial.print("\n");
      }
      else if (i == ((micNum * 3) - 0))
      {
        *micPoints[micNum][2] = coordinateDec;
        Serial.print("*micPoints[micNum][2] = "); //debugging
        Serial.print(*micPoints[micNum][2]);
        Serial.print("\n");
      }
      coordinate = strtok(NULL, ",\n");
      coordinateDec = atof(coordinate);
      i++;
    }
    micNum++;
  }
}

代码编译得很好。当我运行代码时,会出现一个带有以下输出的无限循环:

looping number of mics
*micPoints[micNum][0] = 1.00
        oping number of mics
*micPoints[micNum][0] = 1.00
        oping number of mics
...

当我将float coordinateDec分配给float数组foo[i]时,不会发生这种情况:

  if (i == ((micNum * 3) - 2))
  {
    foo[i] = coordinateDec;
    Serial.print(foo[i]);
    Serial.print("\n");
  }
  else if (i == ((micNum * 3) - 1))
  {
    foo[i] = coordinateDec;
    Serial.print(foo[i]);
    Serial.print("\n");
  }
  else if (i == ((micNum * 3) - 0))
  {
    foo[i] = coordinateDec;
    Serial.print(foo[i]);
    Serial.print("\n");
  }

我获得了正确的输出:

looping number of mics
1.00
1.55
2.54
looping number of mics
2.00
3.34
4.43

为什么通过解除引用运算符分配会将程序发送到无限循环?

0 个答案:

没有答案