![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Programmer
Join Date: Oct 2005
Posts: 52
Rep Power: 3
![]() |
last element trouble
I'm working on these little programming projects for a class (via the internet) and i'm stuck on one of them. The question is:
Given that an array named "a" whose elements are of type int has been declared, assign the value ********* -1 to the last element in a . I was doing: a.getLength - 1 = -1; but i'm getting an error. I tried adding a[].length - 1 but i still get an error saying something has to be in the brackets. |
|
|
|
|
|
#2 |
|
Troll
Join Date: Apr 2005
Location: Texas
Posts: 732
Rep Power: 4
![]() |
[] means index.
When you wrote a[].length, you didn't actually want to index anything. You wanted to take the array and get its length, not the "length" of some (in this case illegaly unspecified) element. To elaborate, a is the array itself, a[insert an index] is an element in the array. So to get the length, that would be a.length. Length is common to all arrays and tells you the number of elements. As you correctly concluded, since arrays start at 0, the last element is array length minus one. Combining those two statements you get a[a.length - 1] to get or set the last element. However, note that if the length is 0, the resulting index would be -1, which would throw an exception (There's not a last element in an empty array anyway, but nobody likes crashes...check for this case). a[a.length - 1] = -1;
__________________
MD5(sig) = bcef75433db02e9ad9bf81d6f7c5c270 |
|
|
|
|
|
#3 |
|
Programmer
Join Date: Oct 2005
Posts: 52
Rep Power: 3
![]() |
haha wow I feel stupid reading your post I feel like that answer should have been common sense... lol Thanks
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| singly-linked list templaste class in C++ w/ example driver | bl00dninja | Show Off Your Open Source Projects | 0 | Sep 11th, 2006 1:05 AM |
| need help passing array values | bjbcartmen | C | 9 | Dec 20th, 2005 10:08 AM |
| Positioning an Element in Screen Space | Dameon | HTML / XHTML / CSS | 4 | Dec 3rd, 2005 7:29 PM |