Pages: [1]   Go Down
Author Topic: What value will the it return?  (Read 318 times)
0 Members and 1 Guest are viewing this topic.
Keynsham, UK
Offline Offline
Full Member
***
Karma: 0
Posts: 224
I like for loops and walks on the beach,
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

If you address a value in an array that doesn't exist, what value will it return?

e.g. int number[4] = {1, 2, 3, 4,}

int val = number[4];

/me
Logged

"C++ : Where friends have access to your private members." - Gavin Russell Baker

Norway@Oslo
Offline Offline
Edison Member
*
Karma: 13
Posts: 2033
loveArduino(true);
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

It will return the contents of the next two adresses in the RAM

Quote

 

void printVariable(char* name, int& x){
  Serial.print(name);
  Serial.print(" - value: ");
  Serial.print(x);
  Serial.print(", @ adress: ");
  Serial.println((int)&x);
}

void setup(){
  
  int intVar = -4;
  int intArray[4] = {1,2,3,4};
  int intArray2[5] = {-5,0,0,0,0};
  
  Serial.begin(9600);
  
  Serial.println("The values and adresses of the intArray:");
  for( byte i=0; i<4; i++){
    Serial.print(i,DEC);
    Serial.print(": ");
    printVariable("intArray", intArray );
  }
  
  //THE BELOW WILL PRINT IDENTICAL VALUES AND ADRESSE
  Serial.println("\nThe value and adress of intVar:");
  printVariable("intVar",intVar);
  
  Serial.println("\nRead nonexistent location -1 in intArray");
  printVariable("intArray[-1]",intArray[-1] );
  
  //THE BELOW WILL PRINT IDENTICAL VALUES AND ADRESSE
  Serial.println("\nThe value and adress of intArray2:");
  printVariable("intArray2[0]",intArray2[0]);
  
  Serial.println("\nRead nonexistent location 4 in intArray");
  printVariable("intArray[4]",intArray[4] );
  
}
  
void loop(){}
 

Quote
The values and adresses of the intArray:

0: intArray - value: 1, @ adress: 1250

1: intArray - value: 2, @ adress: 1252

2: intArray - value: 3, @ adress: 1254

3: intArray - value: 4, @ adress: 1256


The value and adress of intVar:

intVar - value: -4, @ adress: 1248


Read nonexistent location -1 in intArray

intArray[-1] - value: -4, @ adress: 1248



The value and adress of intArray2:

intArray2[0] - value: -5, @ adress: 1258


Read nonexistent location 4 in intArray

intArray[4] - value: -5, @ adress: 1258


Could lead to some nasty bugs.
« Last Edit: April 14, 2009, 03:33:54 pm by AlphaBeta » Logged

Pages: [1]   Go Up
Jump to: