Pointers and references: Difference between revisions
m (Fixed template reference) |
(This task was getting no love, squirreled away in the Language Features category. Moved back to the Programming Tasks section until most of the tasks get a better categorization system.) |
||
Line 1: | Line 1: | ||
{{ |
{{Programming Task}} |
||
In this task, the goal is to desmonstrate common operations on pointers and references. |
In this task, the goal is to desmonstrate common operations on pointers and references. |
Revision as of 02:33, 1 February 2007
In this task, the goal is to desmonstrate common operations on pointers and references.
C++
With pointers:
The following code creates a pointer to an int variable
int var = 3; int* pointer = &var; // or alternatively: int* pointer2(&var);
Access the integer variable through the pointer:
int v = *pointer; // sets v to the value of var (i.e. 3) *pointer = 42; // sets var to 42
Change the pointer to refer to another object
int othervar; pointer = &othervar;
Change the pointer to not point to any object
pointer = 0; // or alternatively: pointer = NULL;
Get a pointer to the first element of an array:
int array[10]; pointer = array; // or alternatively: pointer = &array[0];
Move the pointer to another object in the array
pointer += 3; // pointer now points to array[3] pointer -= 2; // pointer now points to array[1]
Access another object in the same array through the pointer
v = pointer[3]; // accesses third-next object, i.e. array[4] v = pointer[-1]; // accesses previous object, i.e. array[0] // or alternatively v = *(pointer + 3); // array[4] v = *(pointer - 1); // array[0]
With references:
The following code create a reference to an int variable:
int var = 3; int& ref = var; // or alternatively: int& ref2(var);
Access the integer variable through the reference
int v = ref; // sets v to the value of var, that is, 3 ref = 42; // sets var to 42
References cannot be changed to refer to other objects, and cannot (legally) made to refer to no object.
Get a reference to the first element of an array:
int array[10]; int& ref3 = array[0];
Changing the reference to refer to another object of the array is not possible.
Accessing another object of the array through the reference:
v = (&ref)[3]; // read value of array[3]; however doing this is bad style