-3

I have an array with the following values and a variable set to 0 that increases upon added bytes to the array:

data = [0, 0, 0]    
position = 0

I add a byte to the array:

data[position++] = 1

Which now is:

data = [1, 0, 0]
position = 1

My issue: Where 1 is in the array, the position of that byte is 0, but my position is 1. How can I set the position of that byte to 1?

So I can get it like this:

data[position] <- Returns **1** -> data[1]

Now, when I use data[position], it returns 0

khelwood
  • 55,782
  • 14
  • 81
  • 108
Java Swd
  • 3
  • 1
  • 4
  • 1
    When you do `position++` is increments after the scope block. So, it would do `data[0] = 1` and then increment `position` after. If you want it incremented before (which actually uses a tiny bit less memory) you would do `data[++position] = 1` – adprocas Apr 27 '18 at 13:48
  • 2
    of course, because you incremented position... your intention is unclear – Patrick Parker Apr 27 '18 at 13:48
  • It is supposed to increment, because I am working with writing bytes. Write 1 byte increments the position that is being used to read. Thanks for that tip also! – Java Swd Apr 27 '18 at 13:49
  • FYI, Kotlin is not Java. You should pick the correct tag for the programming language you are using. – Patrick Parker Apr 27 '18 at 13:52

3 Answers3

2

By using the postfix increment the position is still 0 when its accessed in data[position++] and only after being accessed is the +1 value added. So you're basically doing data[0] = 1. Use ++position so that position is incremented before its value is accessed.

mthandr
  • 3,062
  • 2
  • 23
  • 33
1

To answer your exact question, you could do this:

data[position - 1]

Comment: But it's true that your question is not clear. When you say "a variable set to 0 that increases upon added bytes to the array", that means that when you add another byte to the array, like say

data[2] = 0

Now data == [1, 0, 1]. But position still equals 1. Who is responsible for incrementing position?

So what would you want to happen here?

martin jakubik
  • 4,168
  • 5
  • 29
  • 42
0

Use data[++position] = 1 instead of data[position++] = 1.

What's just happened?

If you use i++ (postfix) , position is increased by 1 but, the old value of position will be returned into the array index like data[0].

If you use ++i (prefix) , position is increased by 1 and also the new value of position will be returned into the array index like data[1].

In this case, using prefix firstly position increase by one and 1 will be assigned into the first element of the array not zeroth element.

Panduka Nandara
  • 504
  • 6
  • 14