0

I have an array of finite size, say something like uint[100] Arr;.

My question is, if I want to continually push to this array, what happens if it already has 100 uints in it and I push another one? Will I crash? Or will it automatically pop out the first element?

If it does not pop out the first element, am I okay to do something like this:

if (Arr.length == 100) {
    delete Arr[0];
}
Arr.push(new_uint);
1

You can't push to an array of fixed size. (The code you wrote above would not compile.)

push modifies an array's size, so it's an operation that doesn't make sense for a fixed-size array. It only exists for dynamic arrays.

UPDATE

I believe that delete Arr[0] is equivalent to Arr[0] = 0, so it's also not doing anything useful for you.

If you explain what you're trying to do, perhaps people can help more. (It looks like you're trying to implement a deque using a fixed-size array? But what is supposed to happen when you run out of space?)

UPDATE 2

Per the comments, it sounds like you just want a regular circular buffer.

Untested, but I believe this should work:

pragma solidity ^0.4.17;

contract CircularBuffer {
    uint[100] Arr;

    // Represents the index in the array of the oldest element
    uint8 start;

    // Represents the next position to write to
    uint8 end;

    // Represents the size of the data (max of 100)
    uint8 size;

    function append(uint value) public {
        Arr[end] = value;
        end = (end + 1) % 100;

        if (size < 100) {
            size += 1;
        } else {
            // start was just overwritten
            start = (start + 1) % 100;
        }
    }

    function enumerate() public {
        for (uint8 i = 0; i < size; i++) {
            uint value = Arr[(start + i) % 100];
            // do something with value here
        }
    }
}
6
  • In essence, I want to keep the last 100 records. I am trying to implement a deque with a maximum length of elements. So when that length is reached, the oldest element is popped. I guess it doesn't need to be a deque because I don't intend to pop from the other side. But hopefully that makes sense. – Wapiti Sep 25 '17 at 17:44
  • @Wapiti Yeah, sounds like a regular circular buffer will do. See my edit. – user19510 Sep 25 '17 at 20:22
  • Wow, that is cool! It destroys the ordering of the records within the array but I can always get them in their temporal order because of the start index. Thanks;) – Wapiti Sep 25 '17 at 21:09
  • The enumerate function enumerates them in the correct order. – user19510 Sep 25 '17 at 21:47
  • Yes, I saw that. I take it this is a standard data structure? I have not heard of it before. – Wapiti Sep 25 '17 at 22:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.