11

I would like to know if there is any way by which I can create dynamically sized array to avoid runtime error in the code below.

Error:

panic: runtime error: index out of range in Go

Code:

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func nextLargerNodes(head *ListNode) []int {

    var a []int
    var pha int
    hNum := 0
    currNode := head
    pha = 0
    for currNode.Next != nil {
        iter := currNode.Next
        hNum = currNode.Val
        //phb = pha + 1
        for(iter.Next != nil){
            if hNum < iter.Val {
                hNum = iter.Val
                break
            } else if hNum == iter.Val{
                hNum = 0
                break
            }

            iter = iter.Next
        }
        a[pha] = iter.Val
        pha++
        hNum = 0
        currNode = currNode.Next
    }
    return a
}
4
  • I retracted my flag, but here's something perhaps more helpful: stackoverflow.com/questions/3387273/… Commented Aug 10, 2019 at 11:37
  • a = append(a, iter.Val) and you don't need pha any more. Commented Aug 10, 2019 at 11:44
  • 2
    1. No, there's no such thing as a dynamically sized array in Go. 2. You're not using an array at all. You're using a slice. 3. Slices are dynamically sized. Commented Aug 10, 2019 at 13:39
  • 1
    tour.golang.org/moretypes/15 Commented Aug 10, 2019 at 13:55

2 Answers 2

16

You should use append function.

var a []int

is a slice, you can think of it as a "dynamic array". In order to add elements to it, you should use append method. In your code, you used array semantics.

a = append(a, iter.Val)

You can create your slice with a predefined number of elements if you know upfront how many elements you are going to have in your slice.

a := make([]int, 10)

this will create a slice with 10 elements in it.

Sign up to request clarification or add additional context in comments.

Comments

10

Go arrays are fixed in size, but thanks to the builtin append method, we get dynamic behavior. The fact that append returns an object, really highlights the fact that a new array will be created if necessary. The growth algorithm that append uses is to double the existing capacity.

numbers := make([]int, 0)
numbers = append(numbers, 1)
numbers = append(numbers, 2)
fmt.Println(len(numbers)) // == 2

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.