
- Go Tutorial
- Go - Home
- Go - Overview
- Go - Environment Setup
- Go - Program Structure
- Go - Basic Syntax
- Go - Data Types
- Go - Variables
- Go - Constants
- Go - Operators
- Go - Decision Making
- Go - Loops
- Go - Functions
- Go - Scope Rules
- Go - Strings
- Go - Arrays
- Go - Pointers
- Go - Structures
- Go - Slice
- Go - Range
- Go - Maps
- Go - Recursion
- Go - Type Casting
- Go - Interfaces
- Go - Error Handling
- Go Useful Resources
- Go - Questions and Answers
- Go - Quick Guide
- Go - Useful Resources
- Go - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Go - Array of pointers
Before we understand the concept of arrays of pointers, let us consider the following example, which makes use of an array of 3 integers −
package main import "fmt" const MAX int = 3 func main() { a := []int{10,100,200} var i int for i = 0; i < MAX; i++ { fmt.Printf("Value of a[%d] = %d\n", i, a[i] ) } }
When the above code is compiled and executed, it produces the following result −
Value of a[0] = 10 Value of a[1] = 100 Value of a2] = 200
There may be a situation when we want to maintain an array, which can store pointers to an int or string or any other data type available. The following statement declares an array of pointers to an integer −
var ptr [MAX]*int;
This declares ptr as an array of MAX integer pointers. Thus, each element in ptr, now holds a pointer to an int value. The following example makes use of three integers, which will be stored in an array of pointers as follows −
package main import "fmt" const MAX int = 3 func main() { a := []int{10,100,200} var i int var ptr [MAX]*int; for i = 0; i < MAX; i++ { ptr[i] = &a[i] /* assign the address of integer. */ } for i = 0; i < MAX; i++ { fmt.Printf("Value of a[%d] = %d\n", i,*ptr[i] ) } }
When the above code is compiled and executed, it produces the following result −
Value of a[0] = 10 Value of a[1] = 100 Value of a[2] = 200
go_pointers.htm
Advertisements