You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Solidity将固定长度结构体数组改为动态数组时的报错问题咨询

Fixing the Invalid Opcode Error When Using Dynamic Struct Arrays in Solidity 0.4.17

Hey there! I see exactly what's causing that invalid opcode error—let's break it down and fix it right away.

The Root Cause

When you changed your fixed-length array signature[5] public unverified_sig; to a dynamic array signature[] public unverified_sig;, the array starts empty (length 0) by default. Your original add_signature function tries to directly assign values to unverified_sig[0], but that index doesn't exist yet! This array out-of-bounds access triggers a runtime exception, which shows up as the invalid opcode error you're seeing.

The Corrected Code

Here's how to properly modify your contract to use a dynamic array and safely add elements:

pragma solidity ^0.4.17;

contract Signature {
    struct signature {
        string value;
        uint rate;
        address sender_acc;
    }

    // Changed to dynamic array (no fixed length)
    signature[] public unverified_sig; 

    function add_signature(string rec_signature) public {
        // Create a new signature struct instance and push it to the dynamic array
        unverified_sig.push(signature({
            value: rec_signature,
            rate: 0,
            sender_acc: msg.sender
        }));
    }
}

What Changed?

  • Dynamic Array Declaration: We removed the fixed length [5] to make unverified_sig a dynamic array that grows as needed.
  • Safe Element Addition: Instead of trying to write to a non-existent index, we use Solidity's push() method for dynamic arrays. This method automatically creates a new element at the end of the array and initializes it with the struct values we provide.

Alternative Syntax (If You Prefer)

You can also declare a struct variable first before pushing it, which works the same way:

function add_signature(string rec_signature) public {
    signature memory newSig = signature(rec_signature, 0, msg.sender);
    unverified_sig.push(newSig);
}

Why This Works

Dynamic arrays in Solidity 0.4.x don't pre-allocate elements like fixed-length arrays do. push() handles the memory allocation and array length increment automatically, so you never try to access an index that doesn't exist.

Now when you call add_signature(), the function will safely add a new signature to the array without triggering the runtime error.

内容的提问来源于stack exchange,提问作者Shabbar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 15:22:27