×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang Pointers | Find Output Programs | Set 1

This section contains the Golang pointers find output programs (set 1) with their output and explanations.
Submitted by Nidhi, on October 21, 2021

Program 1:

package main

import "fmt"

func changeValue(v *int) {
	*v = 20
}

func main() {
	val := 10
	fmt.Println("Value is: ", val)
	changeValue(&val)
	fmt.Println("Value is: ", val)
}

Output:

Value is:  10
Value is:  20

Explanation:

In the above program, we created two functions changeValue() and main(). The changeValue() function assigns a new value to the specified pointer. In the main() function, created a variable val initialized with 10. Then passed the address of the val variable. Then we printed the updated value of the val variable.


Program 2:

package main

import "fmt"

func changeValue(v *int)

func main() {
	val := 10
	fmt.Println("Value is: ", val)
	changeValue(&val)
	fmt.Println("Value is: ", val)
}

func changeValue(v *int) {
	*v = 20
}

Output:

./prog.go:5:6: missing function body
./prog.go:14:6: changeValue redeclared in this block
	prog.go:5:21: previous declaration

Explanation:

The above program will generate a syntax error because function prototype func changeValue(v *int); is not required in the Go language.


Program 3:

package main

import "fmt"

func main() {
	val := 10

	var ptr *int

	ptr = &val

	*ptr = 50
	fmt.Println("Value is: ", val)
	fmt.Println("Value is: ", *ptr)
}

Output:

Value is:  50
Value is:  50

Explanation:

In the above program, we created a variable val and pointer ptr. Then we assigned the address of val into pointer ptr. After that, we assigned the new value to the *ptr. It will change the value of val. Then we printed the value of val and *ptr.


Program 4:

package main

import "fmt"

func main() {
	var val int = 10
	var ptr1 *int
	var ptr2 **int

	ptr1 = &val
	ptr2 = &ptr1

	**ptr2 = 50
	fmt.Println("Value is: ", val)
	fmt.Println("Value is: ", *ptr1)
	fmt.Println("Value is: ", **ptr2)
}

Output:

Value is:  50
Value is:  50
Value is:  50

Explanation:

In the above program, we created a variable val, ptr1 and ptr2. Then we assigned the address of val into pointer ptr1, and assigned the address into ptr2. After that, we assigned the new value to the **ptr2. It will change the value of val. Then we printed the value of val, *ptr1, and **ptr2.


Program 5:

package main

import "fmt"

func main() {
	var val string = "hello"
	var ptr *string

	ptr = &val
	fmt.Printf("%s\n", *ptr)
	fmt.Printf("%c\n", val[1])
}

Output:

hello
e

Explanation:

In the above program, we created a variable val, ptr. Then we assigned the address of val into pointer ptr. After that, we printed the *ptr and the 2nd character of the string val.

Golang Find Output Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.