-1

I created a 2D slice using the below code. Say I created [3]3] slice -- [[1 2 3],[4 5 6][7 8 9]] But if I update the slice say s[1][1]=99 all changes --> [1 99 3], [4 99 6], [7 99 9]]

However, the second slice I have initialized below with variable cost does behave correctly. Not sure what is wrong:


func CreateSparseM()  *SparseM{
    var m,n,nz int
    fmt.Println("Enter the row count of matrix ")
    fmt.Scan(&m)
    fmt.Println("Enter the column count of matrix ")
    fmt.Scan(&n)
    fmt.Println("Enter the count of Non Zero elements in the matrix ")
    fmt.Scan(&nz)
    r:=make([][]int,m)
    c:=make([]int,n)
    for i:=0;i<m;i++{
        r[i] =  c
    }
    fmt.Println(" r ", r)
    r[1][1] = 99
    fmt.Println(r[1][1])
    fmt.Println(r[0][1])
    //enter the non-zero elements
    var row,col,elem int
    for i:=0;i<nz;i++{
        fmt.Println("Enter row ")
        fmt.Scan(&row)
        fmt.Println("Enter col ")
        fmt.Scan(&col)
        fmt.Println("Enter element ")
        fmt.Scan(&elem)
        r[row][col] = elem
    }
    fmt.Println(r)

    cost:= [][]int{ {1,1,2,2,3,4,4,5,5},
        {2,6,3,7,4,5,7,6,7},
        {25,5,12,10,8,16,14,20,18}}

    fmt.Println(cost)
    cost[1][2]= 777

    fmt.Println(cost)
    sparseM := &SparseM{m,n,nz,r}
    return sparseM
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Learner
  • 65
  • 4

1 Answers1

0

A slice contains a reference to an array, the capacity, and the length of the slice. So the following code:

r:=make([][]int,m)
c:=make([]int,n)
for i:=0;i<m;i++{
   r[i] =  c
}

sets all of r[i] to the same slice c. That is, all r[i] share the same backing array. So if you set r[i][j]=x, you set j'th element of all slices r[i] to x.

The slice you initialized using a literal has three distinct slices, so it does not behave like this.

If you do:

for i:=0;i<m;i++{
   r[i] =  make([]int,n)
}

then you'll have distinct slices for the first case as well.

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
  • Thanks ... Yes that was the key that slice is a pointer and thus using make() inslde the loop will do the trick else all rows were pointing to the same slice. – Learner Mar 05 '20 at 17:10