Pointers and Arrays

Filter Course


Pointers and Arrays

Published by: Zaya

Published date: 18 Jun 2021

Pointers and Arrays Photo

Pointers and Arrays

A pointer is a value that designates the address (i.e., the location in memory), of some value. Pointers are variables that hold a memory location.


There are four fundamental things you need to know about pointers:

  • How to declare them (with the address operator ‘&’: int *pointer = &variable;)
  • How to assign to them (pointer = NULL;)
  • How to reference the value to which the pointer points (known as dereferencing, by using the dereferencing operator ‘*’: value = *pointer;) How they relate to arrays (the vast majority of arrays in C are simple lists, also called “1-dimensional arrays”, but we will briefly cover multi-dimensional arrays with some pointers in a later chapter).
  • Pointers can reference any data type, even functions. We’ll also discuss the relationship of pointers with text strings and the more advanced concept of function pointers.

Declaring pointers

Consider the following snippet of code which declares two pointers:

struct MyStruct {
int m_aNumber;
float num2;
};
int main()
{
int *pJ2;
struct MyStruct *pAnItem;
}
Lines 1-4 define a structure. Line 8 declares a variable that points to an int, and line 9 declares a variable that points to something with structure MyStruct. So to declare a variable as something which points to some type, rather than contains some type, the asterisk (*) is placed before the variable name.
In the following, line 1 declares var1 as a pointer to a long and var2 as a long and not a pointer to along. Inline 2, p3 is declared as a pointer to a pointer to an int.

long * var1, var2;
int ** p3;

Pointer types are often used as parameters to function calls. The following shows how to declare a function that uses a pointer as an argument. Since C passes function arguments by value, to allow a function to modify a value from the calling routine, a pointer to the value must be passed. Pointers to structures are also used as function arguments even when nothing in the struct will be modified in the function. This is done to avoid copying the complete contents of the structure onto the stack. More about pointers as function arguments later.
int MyFunction( struct MyStruct *struct );