3

I have following code piece:

  struct PaymentReceipt{
    uint   start_block;
    uint   end_block;
  }
  PaymentReceipt[] paymentReceiptList;

  function verfiyPayment(uint block_start, uint block_end) returns (bool success) {
    paymentReceiptList.push(PaymentReceipt({start_block: block_start, end_block: block_end }));
    return true;
  }

As I know, each new Struct will be pushed on top of the stack, so latest element (paymentReceiptList.length) will always point to the latest pushed Struct.

https://github.com/ethereum/wiki/wiki/Solidity-Features:

Dynamically-sized storage arrays have a member function push, such that var l = arr.push(el); is equivalent to arr[arr.length++] = el; var l = arr.length;.

For example, Java has following approach that: we can insert the specific element at the specified position in the list.

[Q] Is it possible to push an object into an Array with a given index and shift indexes, like the example on Java?

2 Answers 2

2

There is no built-in method for inserting a value at a specific position in an array. You'll just have to write a loop to do it.

If you're going to be inserting a lot of elements in the middle of the array, it may make more sense to use a linked list instead of an array, so that you aren't doing as many storage writes, which can be expensive.

2
  • I am thinking to implement LinkedList as the implementation in C as via pointer. In order to do that I need to allocate memory space for node and its address. I was not able to obtain its address. struct node{ uint data; uint next; } node head = node(0,0); is it possible to get head's address in the memory?
    – alper
    Commented Jan 29, 2017 at 13:09
  • 1
    I'm not exactly sure what you're asking. For a linked list, you need to keep a pointer to the head separate from the rest of the data structure. Commented Jan 29, 2017 at 18:12
0

A bit outdated answer, but still :) If you can assume you gonna insert no more than N elements at the beginning, you could just reserve them in advance and allocate array size of usual_size + N elements. Also you keep variable offset, so any accessing will be like myArray[offset + i]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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