如何使用C中的标量变量访问数组元素?

时间:2014-01-12 13:10:35

标签: arrays arduino

我想使用数组元素(在本例中为元素3)作为循环变量,给它一个简单的名称,如“c”。 (此代码适用于Arduino,但在标准C中看起来应该类似。) 问题是:有没有办法让编译器接受for-loop中的c = 5语句?

byte array[5];
#define c  (int) (byte *) array[3]  

void setup() {
  Serial.begin(9600);
  Serial.println("this only works with a work-around:");
  Serial.print("address of array: ");
  Serial.println( (int) &array );
  Serial.println("this is the loop:");
  for ( /* what you want is: c = 5 */ 
        /* what the compiler requires: */ array[3] = 5; 
        c < 10; c++) Serial.println(c); 
  // the compiler does not accept c = 5
  Serial.println("this works but it wasts time:");
  while (c != 5) c++;
  for ( ; c < 10; c++) Serial.println(c);
}

void loop() {
}

3 个答案:

答案 0 :(得分:1)

// quod licet int non licet byte
   int array[10]; // byte does not work
// ^^^ that makes the difference

#define c  (int) (byte *) array[3]  
#define d  (int) (byte *) array[4]  

void setup() {
  Serial.begin(9600);
  Serial.println("this is the loop:");
  for (c = 2; c < 5; c++) {     // this loop starts at 2
    for (d = 3; d < 6; d++) {   // this loop starts at 3
      Serial.print(c);
      Serial.print(" ");
      Serial.println(d);
    }
  }
  for (int i = 0; i < 10; i++) Serial.println(array[i]);
}

void loop() {}

答案 1 :(得分:0)

ascii到整数转换器

 c=atoi(array[3]);

希望这对你有所帮助。

答案 2 :(得分:0)

不幸的是,我不得不自己找到它。 这似乎是给某些数组元素赋予名称并在for循环中使用它们的最佳方法(目标是Arduino环境)。

#define SET(x,y) while (x != y) x++
/* thanks to the cleverness of the compiler this macro does not waste time at run-time */

byte array[10];
#define c  (int) (byte *) array[3]  
#define d  (int) (byte *) array[4]  

void setup() {
  Serial.begin(9600);
  Serial.println("this is the loop:");
  SET(c,2);
  for ( ; c < 5; c++) {     // this loop starts at 2
    SET(d,3);
    for ( ; d < 6; d++) {   // this loop starts at 3
      Serial.print(c);
      Serial.print(" ");
      Serial.println(d);
    }
  }
  for (int i = 0; i < 10; i++) Serial.println(array[i]);
}

void loop() {}

当您在结尾打印数组内容时,您会看到循环变量c和d的最后一个值(5和6)。