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

Nim语言索引越界问题求助:代码报错IndexError如何解决?

Fixing the Index Out of Bounds Error in Your Nim Code

Hey there! Let's break down why you're getting that index out of bounds error and how to fix it.

The Root Cause

Nim uses 0-indexed sequences—meaning the first element of a seq is at index 0, and the last valid index is always size - 1 (where size is the length of your sequence). Your code has a key mistake that violates this rule:

  1. Incorrect loop range: You're using for i in 1..size, which makes i go all the way to size itself. But when i equals size, you're trying to access theMap[i]—a position that doesn't exist (since the sequence only goes up to size - 1).
  2. Unnecessary variable declaration: The line var i: int = 0; is redundant because Nim's for loop automatically creates the loop variable for you.

Corrected Code

Here's the fixed version of your code with explanations for each change:

proc makeMap(width: int, size: int): seq[int] =
  var theMap = newSeq[int](size)
  var playerPos: int = 249750
  # Use 0..<size to cover all valid indices (0 to size-1)
  for i in 0..<size:
    if i < width:
      theMap[i] = 2
    elif i == playerPos:
      theMap[i] = 1
    else:
      theMap[i] = 0
  return theMap

var width = 500
var height = 500
var nsize: int = width * height
var myMap = makeMap(width, nsize)
echo "Map: ", myMap

Key Changes Explained

  • Loop range adjustment: 0..<size generates every integer from 0 up to (but not including) size, which perfectly matches the valid indices of your sequence. This eliminates the out-of-bounds access.
  • Removed redundant variable: We got rid of var i: int = 0; since the for loop handles creating i for us.

Quick Check

Your playerPos value (249750) is valid here: since width * height = 250000, the maximum valid index is 249999, so 249750 falls well within the valid range. Just keep this in mind if you ever adjust the width or height values later!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:58:58