Understanding pointers
Published on 2022-01-03
In computer science, a pointer is an object that stores a memory address. This can be that of another value located in computer memory, or in some cases, that of memory-mapped computer hardware. You can declare a pointer in C by stating the type of the pointer, followed by the * operator and the name of the variable:
int* p;
And in Go you declare it by using the keyword var followed by the name of the variable, the * operator and the type of the pointer:
var p *int
There are two main operators you can use on a pointer: referencing(& in C like languages) and dereferencing(* in C like languages).
Referencing
Referencing means taking the address of an existing variable (using & in front of the referenced value) to set a pointer variable. In order to be valid, a pointer must be set to the address of a variable of the same type as the pointer.
// main.c
#include <stdio.h>
int main() {
int* p;
int v;
v = 10;
p = &v; // p references v
printf("%d, %p", v, p);
// output: 10, 0xc000018030
}
// main.go
package main
import "fmt"
func main() {
var p *int
var v int
v = 10
p = &v // p references v
fmt.Printf("%d, %p", v, p)
// output: 10, 0xc000018030
}
Dereferencing
Dereferencing a pointer means using the * operator to retrieve the value from the memory address referenced by the pointer. Like in referencing, the value stored at the address of the pointer must be of the same type
// main.c
#include <stdio.h>
int main() {
int* p;
int v;
v = 10;
p = &v;
int dv = *p;
/* dv now holds the value stored
at the address p points to */
}
// main.go
package main
import "fmt"
func main() {
var p *int
var v int
v = 10
p = &v
dv := *p
/* dv now holds the value stored
at the address p points to */
}
When to use pointers?
In C:
In general the answer I find is: don’t. Pointers should be used when you can’t use anything else, for example: lack appropriate functionality, missing data types (e.g., strings in C) or for pure performance. In C you don’t have any support for complex datatypes such as a string. There is also no way of passing a variable “by reference” to a function as other languages (e.g., JavaScript where objects are passed by “copy of reference”).
In Go:
Due to Go having a string type and passing pointers instead of values, it is often slower (because Go is a garbage collected language). The use cases for pointers are different than in C.
A case where using a pointer is more performant than using a value is when you have to handle a large struct with a lot of data.
Mutability can also be one reason to use pointers in Go as it’s the only way to mutate a value in the language.
This was just a quick overview/introduction on pointers and a lot of information was left out but this should help you at least understand what pointers are about in general.