Shop OBEX P1 Docs P2 Docs Learn Events
Accessing part of an array that doesn't exist — Parallax Forums

Accessing part of an array that doesn't exist

piguy101piguy101 Posts: 248
edited 2014-01-23 14:15 in Propeller 1
Suppose that I had an array of ten bytes called memory. So: byte memory[10]. What would happen if part of the code tried to set or read parts of the array that do not exist such as memory[11]:=0 or x:=memory[11]? My guess is that the first code would not do anything and x in the second code would be set to zero. Is this correct?

Comments

  • Duane DegnDuane Degn Posts: 10,588
    edited 2014-01-23 12:35
    memory[11] := 1 would set the memory location two places after the last element in the array to one. If you had:
    VAR
      byte memory[10], x, y, z
    

    Then
    memory[11] := 1
    

    would have the same effect as
    y := 1
    

    Remember with ten elements in the array, the highest index is 9 (since they start with zero).

    So:
    memory[10] := 1
    

    would have the same effect as
    x := 1
    

    If you use
    memory[13] := 1
    

    Then you're in danger of overwriting your program.
  • piguy101piguy101 Posts: 248
    edited 2014-01-23 12:59
    Thanks. I made a simple game of simon with an array of 255 elements and wondered what would happen if I could memorize that many in a row. I just tested the code, and it does simply read the next variable after the array rather than crashing. This would have caused a huge headache if the Prop had less RAM.
  • kwinnkwinn Posts: 8,697
    edited 2014-01-23 14:13
    If it is possible that the array index (the i part of memory(i)) could be beyond the end of the data array you would want to make sure it is in bounds before using it by comparing i to the maximum value.
  • David BetzDavid Betz Posts: 14,516
    edited 2014-01-23 14:15
    kwinn wrote: »
    If it is possible that the array index (the i part of memory(i)) could be beyond the end of the data array you would want to make sure it is in bounds before using it by comparing i to the maximum value.
    Good advice and keep in mind that if your array is declared like this:
    VAR
      byte memory[10], x, y, z
    
    Then you want to check that your index is >= 0 and < 10. So memory[10] is outside of the bounds of this array since the index must be in the range of 0 to 9.
Sign In or Register to comment.