Go Down

Topic: What value will the it return? (Read 334 times) previous topic - next topic

BetaDelta

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
"C++ : Where friends have access to your private members." - Gavin Russell Baker

AlphaBeta

#1
Apr 14, 2009, 09:49 pm Last Edit: Apr 14, 2009, 10:33 pm by AlphaBeta Reason: 1
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.

Go Up