Variables

Pointers and References in C#

To store an address in memory of a variable. A pointer is a variable itself and has a value whereas a reference only has a variable that it is referencing.


Syntax
dataType *pointerName = &Variable; //Pointer 

ref dataType Variable; //Reference 

dataType *pointerName = malloc( sizeof (*pointerName)); 
//Memory allocation of the pointer, of whatever data type it is. 

free(pointerName); //Free the memory used by the pointer.

Notes

A pointer can be reassigned, set to NULL, incremented/decremented, etc, while a reference can only refer to one object (they cannot reference NULL).

You can take the address of a pointer, but you cannot take the address of a reference.

Generally we use references in function parameters and return types, whereas we use pointers to implement data structures/algorithms.

Since a pointer has memory, it needs to allocate the memory its using (to the size of its data type) and must be freed after use of the pointer, (using stackalloc).

'fixed' is used to temporarily fix a variable so its address can be obtained.


Example
int x = 5; int *pointer = NULL; 
int *pointer = &x; 
Function(ref value);

Add to Slack

< Constants   |   Arrays >

© 2019 SyntaxDB. All Rights Reserved.