# C Programming/Pointers and arrays

!Pointer *a* pointing to variable *b*. Note that *b* stores a number,
whereas *a* stores the address of *b* in memory
(1462)"){width="180"}
A **pointer "wikilink")** 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:

``` {.c .numberLines}
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 that 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 a long. In line 2, `p3` is
declared as a pointer to a pointer to an int.

``` c
long  *  var1, var2;
int   ** p3;
```

Pointer types are often used as parameters to function calls. The
following shows how to declare a function which uses a pointer as an
argument. Since C passes function arguments by value, in order 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.

``` c
int MyFunction(struct MyStruct *pStruct);
```

## Assigning values to pointers

So far we\'ve discussed how to declare pointers. The process of
assigning values to pointers is next. To assign the address of a
variable to a pointer, the `&` or \'address of\' operator is used.

``` c
int myInt;
int *pPointer;
struct MyStruct dvorak;
struct MyStruct *pKeyboard;

pPointer = &myInt;
pKeyboard = &dvorak;
```

Here, pPointer will now reference myInt and pKeyboard will reference
dvorak.

Pointers can also be assigned to reference dynamically allocated memory.
The malloc() and calloc() functions are often used to do this.

``` c
#include <stdlib.h>
/* ... */
struct MyStruct *pKeyboard;
/* ... */
pKeyboard = malloc(sizeof *pKeyboard);
```

The malloc function returns a pointer to dynamically allocated memory
(or NULL if unsuccessful). The size of this memory will be appropriately
sized to contain the MyStruct structure.

The following is an example showing one pointer being assigned to
another and of a pointer being assigned a return value from a function.

``` c
static struct MyStruct val1, val2, val3, val4;

struct MyStruct *ASillyFunction( int b )
{
    struct MyStruct *myReturn;

    if (b == 1) myReturn = &val1;
    else if (b==2) myReturn = &val2;
    else if (b==3) myReturn = &val3;
    else myReturn = &val4;

    return myReturn;
}

struct MyStruct *strPointer;
int     *c, *d;
int     j;

c = &j;                           /* pointer assigned using & operator */
d = c;                            /* assign one pointer to another     */
strPointer = ASillyFunction( 3 ); /* pointer returned from a function. */
```

When returning a pointer from a function, do not return a pointer that
points to a value that is local to the function or that is a pointer to
a function argument. Pointers to local variables become invalid when the
function exits. In the above function, the value returned points to a
static variable. Returning a pointer to dynamically allocated memory is
also valid.

## Pointer dereferencing

!The pointer `p` points to the variable
`a`.{width="300"}
To access a value to which a pointer points, the `*` operator is used.
Another operator, the `->` operator is used in conjunction with pointers
to structures. Here\'s a short example.

``` c
int   c, d;
int   *pj;
struct MyStruct astruct;
struct MyStruct *bb;

c   = 10;
pj  = &c;             /* pj points to c */
d   = *pj;            /* d is assigned the value to which pj points, 10 */
pj  = &d;             /* now points to d */
*pj = 12;             /* d is now 12 */

bb = &astruct;
(*bb).m_aNumber = 3;  /* assigns 3 to the m_aNumber member of astruct */
bb->num2 = 44.3;      /* assigns 44.3 to the num2 member of astruct   */
*pj = bb->m_aNumber;  /* equivalent to d = astruct.m_aNumber;          */
```

The expression `bb->m_aNumber` is entirely equivalent to
`(*bb).m_aNumber`. They both access the `m_aNumber` element of the
structure pointed to by `bb`. There is one more way of dereferencing a
pointer, which will be discussed in the following section.

When dereferencing a pointer that points to an invalid memory location,
an error often occurs which results in the program terminating. The
error is often reported as a segmentation error. A common cause of this
is failure to initialize a pointer before trying to dereference it.

C is known for giving you just enough rope to hang yourself, and pointer
dereferencing is a prime example. You are quite free to write code that
accesses memory outside that which you have explicitly requested from
the system. And many times, that memory may appear as available to your
program due to the vagaries of system memory allocation. However, even
if 99 executions allow your program to run without fault, that 100th
execution may be the time when your \"memory pilfering\" is caught by
the system and the program fails. Be careful to ensure that your pointer
offsets are within the bounds of allocated memory!

The declaration `void *somePointer;` is used to declare a pointer of
some nonspecified type. You can assign a value to a void pointer, but
you must cast the variable to point to some specified type before you
can dereference it. Pointer arithmetic is also not valid with `void *`
pointers.

## Pointers and Arrays

Up to now, we\'ve carefully been avoiding discussing arrays in the
context of pointers. The interaction of pointers and arrays can be
confusing but here are two fundamental statements about it:

-   A variable declared as an array of some type acts as a pointer to
    that type. When used by itself, it points to the first element of
    the array.
-   A pointer can be indexed like an array name.

The first case often is seen to occur when an array is passed as an
argument to a function. The function declares the parameter as a
pointer, but the actual argument may be the name of an array. The second
case often occurs when accessing dynamically allocated memory.

Let\'s look at examples of each. In the following code, the call to
`calloc()` effectively allocates an array of struct MyStruct items.

``` c
struct MyStruct {
    int someNumber;
    float otherNumber;
};

float returnSameIfAnyEquals(struct MyStruct *workingArray, int size, int bb)
{
    /* Go through the array and check if any value in someNumber is equal to bb. If
     * any value is, return the value in otherNumber. If no values are equal to bb,
     * return 0.0f. */
    for (int i = 0; i < size; i++) {
        if (workingArray[i].someNumber == bb ) {
            return workingArray[i].otherNumber;
        }
    }
    return 0.0f;
}

// Declare our variables
float  someResult;
int    someSize;
struct MyStruct myArray[4];
struct MyStruct *secondArray; // Notice that this is a pointer

const int ArraySize = sizeof(myArray) / sizeof(*myArray);

// Initialization of myArray occurs
someResult = returnSameIfAnyEquals(myArray, ArraySize, 4);

secondArray = calloc(someSize, sizeof(struct MyStruct));
for (int i = 0; i < someSize; i++) {
    /* Fill secondArray with some data */
    secondArray[i].someNumber = i * 2;
    secondArray[i].otherNumber = 0.304f * i * i;
}
```

Pointers and array names can pretty much be used interchangeably;
however, there are exceptions. You cannot assign a new pointer value to
an array name. The array name will always point to the first element of
the array. In the function `returnSameIfAnyEquals`, you could however
assign a new value to workingArray, as it is just a pointer to the first
element of workingArray. It is also valid for a function to return a
pointer to one of the array elements from an array passed as an argument
to a function. A function should never return a pointer to a local
variable, even though the compiler will probably not complain.

When declaring parameters to functions, declaring an array variable
without a size is equivalent to declaring a pointer. Often this is done
to emphasize the fact that the pointer variable will be used in a manner
equivalent to an array.

``` c
/* Two equivalent function prototypes */

int LittleFunction(int *paramN);
int LittleFunction(int paramN[]);
```

Now we\'re ready to discuss pointer arithmetic. You can add and subtract
integer values to/from pointers. If myArray is declared to be some type
of array, the expression `*(myArray+j)`, where j is an integer, is
equivalent to `myArray[j]`. For instance, in the above example where we
had the expression `secondArray[i].otherNumber`, we could have written
that as `(*(secondArray+i)).otherNumber` or more simply
`(secondArray+i)->otherNumber`.

Note that for addition and subtraction of integers and pointers, the
value of the pointer is not adjusted by the integer amount, but is
adjusted by the amount multiplied by the size of the type to which the
pointer refers in bytes. (For example, `pointer + x` can be thought of
as `pointer + (x * sizeof(*type))`.)

One pointer may also be subtracted from another, provided they point to
elements of the same array (or the position just beyond the end of the
array). If you have a pointer that points to an element of an array, the
index of the element is the result when the array name is subtracted
from the pointer. Here\'s an example.

``` c
struct MyStruct someArray[20];
struct MyStruct *p2;
int i;

/* array initialization .. */

for (p2 = someArray; p2 < someArray+20;  ++p2) {
    if (p2->num2 > testValue)
        break;
}
i = p2 - someArray;
```

You may be wondering how pointers and multidimensional arrays interact.
Let\'s look at this a bit in detail. Suppose A is declared as a two
dimensional array of floats (`float A[D1][D2];`) and that pf is declared
a pointer to a float. If pf is initialized to point to A\[0\]\[0\], then
\*(pf+1) is equivalent to A\[0\]\[1\] and \*(pf+D2) is equivalent to
A\[1\]\[0\]. The elements of the array are stored in row-major order.

``` c

float A[6][8];
float *pf;
pf = &A[0][0];
*(pf+1) = 1.3;   /* assigns 1.3 to A[0][1] */
*(pf+8) = 2.3;   /* assigns 2.3 to A[1][0] */
```

Let\'s look at a slightly different problem. We want to have a two
dimensional array, but we don\'t need to have all the rows the same
length. What we do is declare an array of pointers. The second line
below declares A as an array of pointers. Each pointer points to a
float. Here\'s some applicable code:

``` c
float  linearA[30];
float *A[6];

A[0] = linearA;              /*  5 - 0 = 5 elements in row  */
A[1] = linearA + 5;          /* 11 - 5 = 6 elements in row  */
A[2] = linearA + 11;         /* 15 - 11 = 4 elements in row */
A[3] = linearA + 15;         /* 21 - 15 = 6 elements        */
A[4] = linearA + 21;         /* 25 - 21 = 4 elements        */
A[5] = linearA + 25;         /* 30 - 25 = 5 elements        */

*A[3][2] = 3.66;          /* assigns 3.66 to linearA[17];     */
*A[3][-3] = 1.44;         /* refers to linearA[12];
                             negative indices are sometimes useful. But avoid using them as much as possible. */
```

We also note here something curious about array indexing. Suppose
`myArray` is an array and `i` is an integer value. The expression
`myArray[i]` is equivalent to `i[myArray]`. The first is equivalent to
`*(myArray+i)`, and the second is equivalent to `*(i+myArray)`. These
turn out to be the same, since the addition is commutative.

Pointers can be used with pre-increment or post-decrement, which is
sometimes done within a loop, as in the following example. The increment
and decrement applies to the pointer, not to the object to which the
pointer refers. In other words, `*pArray++` is equivalent to
`*(pArray++)`.

``` c
long  myArray[20];
long  *pArray;
int   i;

/* Assign values to the entries of myArray */
pArray = myArray;
for (i=0; i<10; ++i) {
    *pArray++ = 5 + 3*i + 12*i*i;
    *pArray++ = 6 + 2*i + 7*i*i;
}
```

## Pointers in Function Arguments

Often we need to invoke a function with an argument that is itself a
pointer. In many instances, the variable is itself a parameter for the
current function and may be a pointer to some type of structure. The
ampersand (**`&`**) character is not needed in
this circumstance to obtain a pointer value, as the variable is itself a
pointer. In the example below, the variable `pStruct`, a pointer, is a
parameter to function `FunctTwo`, and is passed as an argument to
`FunctOne`.

The second parameter to `FunctOne` is an int. Since in function
`FunctTwo`, `mValue` is a pointer to an int, the pointer must first be
dereferenced using the \* operator, hence the second argument in the
call is `*mValue`. The third parameter to function `FunctOne` is a
pointer to a long. Since `pAA` is itself a pointer to a long, no
ampersand is needed when it is used as the third argument to the
function.

``` c
int FunctOne(struct someStruct *pValue, int iValue, long *lValue)
{
    /*  do some stuff ... */
    return 0;
}

int FunctTwo(struct someStruct *pStruct, int *mValue)
{
    int j;
    long  AnArray[25];
    long *pAA;

    pAA = &AnArray[13];
    j = FunctOne( pStruct, *mValue, pAA ); /* pStruct already holds the address that the pointer will point to; there is no need to get the address of anything.*/
    return j;
}
```

## Pointers and Text Strings

Historically, text strings in C have been implemented as arrays of
characters, with the last byte in the string being a zero, or the null
character \'\\0\'. Most C implementations come with a standard library
of functions for manipulating strings. Many of the more commonly used
functions expect the strings to be null terminated strings of
characters. To use these functions requires the inclusion of the
standard C header file \"string.h\".

A statically declared, initialized string would look similar to the
following:

``` c
static const char *myFormat = "Total Amount Due: %d";
```

The variable `myFormat` can be viewed as an array of 21 characters.
There is an implied null character (\'\\0\') tacked on to the end of the
string after the \'d\' as the 21st item in the array. You can also
initialize the individual characters of the array as follows:

``` c
static const char myFlower[] = { 'P', 'e', 't', 'u', 'n', 'i', 'a', '\0' };
```

An initialized array of strings would typically be done as follows:

``` c
static const char *myColors[] = {
    "Red", "Orange", "Yellow", "Green", "Blue", "Violet" };
```

The initialization of an especially long string can be split across
lines of source code as follows.

``` c
static char *longString = "Hello. My name is Rudolph and I work as a reindeer "
    "around Christmas time up at the North Pole.  My boss is a really swell guy."
    " He likes to give everybody gifts.";
```

The library functions that are used with strings are discussed in a
later chapter.

## Pointers to Functions

C also allows you to create pointers to functions. Pointers to functions
syntax can get rather messy. As an example of this, consider the
following functions:

``` c
static int Z = 0;

int *pointer_to_Z(int x) {
    /* function returning integer pointer, not pointer to function */
    return &Z;
}

int get_Z(int x) {
    return Z;
}

int (*function_pointer_to_Z)(int); // pointer to function taking an int as argument and returning an int
function_pointer_to_Z = &get_Z;

printf("pointer_to_Z output: %d\n", *pointer_to_Z(3));
printf("function_pointer_to_Z output: %d", (*function_pointer_to_Z)(3));
```

Declaring a typedef to a function pointer generally clarifies the code.
Here\'s an example that uses a function pointer, and a void \* pointer
to implement what\'s known as a callback. The `DoSomethingNice` function
invokes a caller supplied function `TalkJive` with caller data. Note
that `DoSomethingNice` really doesn\'t know anything about what
`dataPointer` refers to.

``` c
typedef  int (*MyFunctionType)( int, void *);      /* a typedef for a function pointer */

#define THE_BIGGEST 100

int DoSomethingNice( int aVariable, MyFunctionType aFunction, void *dataPointer )
{
    int rv = 0;
    if (aVariable < THE_BIGGEST) {
       /* invoke function through function pointer (old style) */
       rv = (*aFunction)(aVariable, dataPointer );
     } else {
         /* invoke function through function pointer (new style) */
       rv = aFunction(aVariable, dataPointer );
    };
    return rv;
}

typedef struct {
    int    colorSpec;
    char   *phrase;
} DataINeed;

int TalkJive( int myNumber, void *someStuff )
{
    /* recast void * to pointer type specifically needed for this function */
    DataINeed *myData = someStuff;
    /* talk jive. */
    return 5;
}

static DataINeed sillyStuff = { BLUE, "Whatcha talkin 'bout Willis?" };

DoSomethingNice( 41, &TalkJive,  &sillyStuff );
```

Some versions of C may not require an ampersand preceding the `TalkJive`
argument in the `DoSomethingNice` call. Some implementations may require
specifically casting the argument to the `MyFunctionType` type, even
though the function signature exacly matches that of the typedef.

Function pointers can be useful for implementing a form of polymorphism
in C. First one declares a structure having as elements function
pointers for the various operations to that can be specified
polymorphically. A second base object structure containing a pointer to
the previous structure is also declared. A class is defined by extending
the second structure with the data specific for the class, and static
variable of the type of the first structure, containing the addresses of
the functions that are associated with the class. This type of
polymorphism is used in the standard library when file I/O functions are
called.

A similar mechanism can also be used for implementing a state
machine in C. A structure is defined
which contains function pointers for handling events that may occur
within state, and for functions to be invoked upon entry to and exit
from the state. An instance of this structure corresponds to a state.
Each state is initialized with pointers to functions appropriate for the
state. The current state of the state machine is in effect a pointer to
one of these states. Changing the value of the current state pointer
effectively changes the current state. When some event occurs, the
appropriate function is called through a function pointer in the current
state.

### Practical use of function pointers in C

Function pointers are mainly used to reduce the complexity of switch
statement. Example with switch statement:

``` c
#include <stdio.h>
int add(int a, int b);
int sub(int a, int b);
int mul(int a, int b);
int div(int a, int b);
int main()
{
    int i, result;
    int a=10;
    int b=5;
    printf("Enter the value between 0 and 3 : ");
    scanf("%d",&i);
    switch(i)
    {
        case 0:  result = add(a,b); break;
        case 1:  result = sub(a,b); break;
        case 2:  result = mul(a,b); break;
        case 3:  result = div(a,b); break;
    }
}
int add(int i, int j)
{
    return (i+j);
}
int sub(int i, int j)
{
    return (i-j);
}
 int mul(int i, int j)
{
    return (i*j);
}
int div(int i, int j)
{
    return (i/j);
}
```

Without using a switch statement:

``` c
#include <stdio.h>
int add(int a, int b);
int sub(int a, int b);
int mul(int a, int b);
int div(int a, int b);
int (*oper[4])(int a, int b) = {add, sub, mul, div};
int main()
{
    int i,result;
    int a=10;
    int b=5;
    printf("Enter the value between 0 and 3 : ");
    scanf("%d",&i);
    result = operi;
}
int add(int i, int j)
{
    return (i+j);
}
int sub(int i, int j)
{
    return (i-j);
}
int mul(int i, int j)
{
    return (i*j);
}
int div(int i, int j)
{
    return (i/j);
}
```

Function pointers may be used to create a struct member function:

``` c
typedef struct
{
    int (*open)(void);
    void (*close)(void);
    int (*reg)(void);
} device;

int my_device_open(void)
{
    /* ... */
}

void my_device_close(void)
{
    /* ... */
}

void register_device(void)
{
    /* ... */
}

device create(void)
{
    device my_device;
    my_device.open = my_device_open;
    my_device.close = my_device_close;
    my_device.reg = register_device;
    my_device.reg();
    return my_device;
}
```

Use to implement this pointer (following code must be placed in
library).

``` c
static struct device_data
{
    /* ... here goes data of structure ... */
};

static struct device_data obj;

typedef struct
{
    int (*open)(void);
    void (*close)(void);
    int (*reg)(void);
} device;

static struct device_data create_device_data(void)
{
    struct device_data my_device_data;
    /* ... here goes constructor ... */
    return my_device_data;
}

/* here I omit the my_device_open, my_device_close and register_device functions */

device create_device(void)
{
    device my_device;
    my_device.open = my_device_open;
    my_device.close = my_device_close;
    my_device.reg = register_device;
    my_device.reg();
    return my_device;
}
```

## Examples of pointer constructs

Below are some example constructs which may aid in creating your
pointer.

``` c
int i;          // integer variable 'i'
int *p;         // pointer 'p' to an integer
int a[];        // array 'a' of integers
int f();        // function 'f' with return value of type integer
int **pp;       // pointer 'pp' to a pointer to an integer
int (*pa)[];    // pointer 'pa' to an array of integer
int (*pf)();    // pointer 'pf' to a function with return value integer
int *ap[];      // array 'ap' of pointers to an integer
int *fp();      // function 'fp' which returns a pointer to an integer
int ***ppp;     // pointer 'ppp' to a pointer to a pointer to an integer
int (**ppa)[];  // pointer 'ppa' to a pointer to an array of integers
int (**ppf)();  // pointer 'ppf' to a pointer to a function with return value of type integer
int *(*pap)[];  // pointer 'pap' to an array of pointers to an integer
int *(*pfp)();  // pointer 'pfp' to function with return value of type pointer to an integer
int **app[];    // array of pointers 'app' that point to pointers to integer values
int (*apa[])[]; // array of pointers 'apa' to arrays of integers
int (*apf[])(); // array of pointers 'apf' to functions with return values of type integer
int ***fpp();   // function 'fpp' which returns a pointer to a pointer to a pointer to an int
int (*fpa())[]; // function 'fpa' with return value of a pointer to array of integers
int (*fpf())(); // function 'fpf' with return value of a pointer to function which returns an integer
```

## sizeof

The sizeof operator is often used to refer to the size of a static array
declared earlier in the same function.

To find the end of an array (example from wikipedia:Buffer
overflow):

``` c
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
  char buffer[10];
  if (argc < 2)
  {
    fprintf(stderr, "USAGE: %s string\n", argv[0]);
    return 1;
  }
  strncpy(buffer, argv[1], sizeof(buffer));
  buffer[sizeof(buffer) - 1] = '\0';
  return 0;
}
```

To iterate over every element of an array, use

``` c
 #define NUM_ELEM(x) (sizeof (x) / sizeof (*(x)))

 for( i = 0; i < NUM_ELEM(array); i++ )
 {
     /* do something with array[i] */
     ;
 }
```

Note that the `sizeof` operator only works on things defined earlier in
the same function. The compiler replaces it with some fixed constant
number. In this case, the `buffer` was declared as an array of 10
char\'s earlier in the same function, and the compiler replaces
`sizeof(buffer)` with the number 10 at compile time (equivalent to us
hard-coding 10 into the code in place of `sizeof(buffer)`). The
information about the length of `buffer` is not actually stored anywhere
in memory (unless we keep track of it separately) and cannot be
programmatically obtained at run time from the array/pointer itself.

Often a function needs to know the size of an array it was given \-- an
array defined in some other function. For example,

``` c
/* broken.c - demonstrates a flaw */

#include <stdio.h>
#include <string.h>
#define NUM_ELEM(x) (sizeof (x) / sizeof (*(x)))

int sum( int input_array[] ){
  int sum_so_far = 0;
  int i;
  for( i = 0; i < NUM_ELEM(input_array); i++ ) // WON'T WORK -- input_array wasn't defined in this function.
  {
    sum_so_far += input_array[i];
  };
  return( sum_so_far );
}

int main(int argc, char *argv[])
{
  int left_array[] = { 1, 2, 3 };
  int right_array[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
  int the_sum = sum( left_array );
  printf( "the sum of left_array is: %d", the_sum );
  the_sum = sum( right_array );
  printf( "the sum of right_array is: %d", the_sum );

  return 0;
}
```

Unfortunately, (in C and C++) the length of the array cannot be obtained
from an array passed in at run time, because (as mentioned above) the
size of an array is not stored anywhere. The compiler always replaces
sizeof with a constant. This sum() routine needs to handle more than
just one constant length of an array.

There are some common ways to work around this fact:

-   Write the function to require, for each array parameter, a
    \"length\" parameter (which has type \"size_t\"). (Typically we use
    sizeof at the point where this function is called).
-   Use of a convention, such as a null-terminated
    string to mark the end
    of the array.
-   Instead of passing raw arrays, pass a structure that includes the
    length of the array (such as \".length\") as well as the array (or a
    pointer to the first element); similar to the `string` or `vector`
    classes in C++.

``` c
/* fixed.c - demonstrates one work-around */

#include <stdio.h>
#include <string.h>
#define NUM_ELEM(x) (sizeof (x) / sizeof (*(x)))

int sum( int input_array[], size_t length ){
  int sum_so_far = 0;
  int i;
  for( i = 0; i < length; i++ )
  {
    sum_so_far += input_array[i];
  };
  return( sum_so_far );
}

int main(int argc, char *argv[])
{
  int left_array[] = { 1, 2, 3, 4 };
  int right_array[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
  int the_sum = sum( left_array, NUM_ELEM(left_array) ); // works here, because left_array is defined in this function
  printf( "the sum of left_array is: %d", the_sum );
  the_sum = sum( right_array, NUM_ELEM(right_array) ); // works here, because right_array is defined in this function
  printf( "the sum of right_array is: %d", the_sum );

  return 0;
}
```

It\'s worth mentioning that sizeof operator has two variations:
`sizeof (``<i>`{=html}`type``</i>`{=html}`)` (for instance:
`sizeof (int)` or `sizeof (struct some_structure)`) and
`sizeof ``<i>`{=html}`expression``</i>`{=html} (for instance:
`sizeof some_variable.some_field` or `sizeof 1`).

## External Links

```{=html}
<div class="noprint">
```
!Pointer Fun with
Binky.ogg "Pointer Fun with Binky")

```{=html}
</div>
```
-   \"Common Pointer
    Pitfalls\"
    by Dave Marshall

de:C-Programmierung: Zeiger
fr:Programmation C/Pointeurs
it:C/Vettori e puntatori/Interscambiabilità tra puntatori e
vettori
pl:C/Wskaźniki


# C Programming/Memory management

In C, you have already considered creating variables for use in the
program. You have created some arrays for use, but you may have already
noticed some limitations:

-   the size of the array must be known beforehand
-   the size of the array cannot be changed in the duration of your
    program

*Dynamic memory allocation* in C is a way of circumventing these
problems.

## The `malloc` function

``` c
#include <stdlib.h>
void *calloc(size_t nmemb, size_t size);
void free(void *ptr);
void *malloc(size_t size);
void *realloc(void *ptr, size_t size);
```

The standard C function `malloc` is the means of implementing dynamic
memory allocation. It is defined in stdlib.h or malloc.h, depending on
what operating system you may be using. Malloc.h contains only the
definitions for the memory allocation functions and not the rest of the
other functions defined in stdlib.h. Usually you will not need to be so
specific in your program, and if both are supported, you should use
\<stdlib.h\>, since that is ANSI C, and what we will use here.

The corresponding call to release allocated memory back to the operating
system is `free`.

When dynamically allocated memory is no longer needed, `free` should be
called to release it back to the memory pool. Overwriting a pointer that
points to dynamically allocated memory can result in that data becoming
inaccessible. If this happens frequently, eventually the operating
system will no longer be able to allocate more memory for the process.
Once the process exits, the operating system is able to free all
dynamically allocated memory associated with the process.

Let\'s look at how dynamic memory allocation can be used for arrays.

Normally when we wish to create an array we use a declaration such as

``` c
int array[10];
```

Recall `array` can be considered a pointer which we use as an array. We
specify the length of this array is 10 `int`s. After `array[0]`, nine
other integers have space to be stored consecutively.

Sometimes it is not known at the time the program is written how much
memory will be needed for some data; for example, when it depends upon
user input. In this case we would want to dynamically allocate required
memory after the program has started executing. To do this we only need
to declare a pointer, and invoke `malloc` when we wish to make space for
the elements in our array, *or*, we can tell `malloc` to make space when
we first initialize the array. Either way is acceptable and useful.

We also need to know how much an int takes up in memory in order to make
room for it; fortunately this is not difficult, we can use C\'s builtin
`sizeof` operator. For example, if `sizeof(int)` yields 4, then one
`int` takes up 4 bytes. Naturally, `2*sizeof(int)` is how much memory we
need for 2 `int`s, and so on.

So how do we `malloc` an array of ten `int`s like before? If we wish to
declare and make room in one hit, we can simply say

``` c
int *array = malloc(10*sizeof(int));
```

We only need to declare the pointer; `malloc` gives us some space to
store the 10 `int`s, and returns the pointer to the first element, which
is assigned to that pointer.

**Important note!** `malloc` does *not* initialize the array; this means
that the array may contain random or unexpected values! Like creating
arrays without dynamic allocation, the programmer must initialize the
array with sensible values before using it. Make sure you do so, too.
(\'\'See later the function `memset` for a simple method.)

It is not necessary to immediately call `malloc` after declaring a
pointer for the allocated memory. Often a number of statements exist
between the declaration and the call to `malloc`, as follows:

``` c
int *array = NULL;
printf("Hello World!!!");
/* more statements */
array = malloc(10*sizeof(int)); /* delayed allocation */
/* use the array */
```

A more practical example of dynamic memory allocation would be the
following:

> Given an array of 10 integers, remove all duplicate elements from the
> array, and create a new array without duplicate elements (a
> set "wikilink")).

A simple algorithm to remove duplicate elements:

``` {.c .numberLines}
    int arrl = 10; // Length of the initial array
    int arr[10] = {1, 2, 2, 3, 4, 4, 5, 6, 5, 7}; // A sample array, containing several duplicate elements

    for (int x = 0; x < arrl; x++)
    {
        for (int y = x + 1; y < arrl; y++)
        {
            if (arr[x] == arr[y])
            {
                for (int s = y; s < arrl; s++)
                {
                    if (!(s + 1 == arrl))
                        arr[s] = arr[s + 1];
                }

                arrl--;
                y--;
            }
        }
    }
```

Because the length of our new array depends on the input, it must be
dynamically allocated:

``` c
int *newArray = malloc(arrl*sizeof(int));
```

The above array will currently contain unexpected values, so we must use
`memcpy` to set our dynamically allocated memory block to the new
values:

``` c
memcpy(newArray, arr, arrl*sizeof(int));
```

### Error checking

When we want to use `malloc`, we have to be mindful that the pool of
memory available to the programmer is *finite*. Even if a modern PC will
have at least an entire gigabyte of memory, it is still possible and
conceivable to run out of it! In this case, `malloc` will return `NULL`.
In order to stop the program crashing from having no more memory to use,
one should always check that malloc has not returned `NULL` before
attempting to use the memory; we can do this by

``` c
int *pt = malloc(3 * sizeof(int));
if(pt == NULL)
{
   fprintf(stderr, "Out of memory, exiting\n");
   exit(1);
}
```

Of course, suddenly quitting as in the above example is not always
appropriate, and depends on the problem you are trying to solve and the
architecture you are programming for. For example, if the program is a
small, non critical application that\'s running on a desktop quitting
may be appropriate. However if the program is some type of editor
running on a desktop, you may want to give the operator the option of
saving their tediously entered information instead of just exiting the
program. A memory allocation failure in an embedded processor, such as
might be in a washing machine, could cause an automatic reset of the
machine. For this reason, many embedded systems designers avoid dynamic
memory allocation altogether.

## The `calloc` function

The `calloc` function allocates space for an array of items and
initializes the memory to zeros. The call
`mArray = calloc( count, sizeof(struct V))` allocates `count` objects,
each of whose size is sufficient to contain an instance of the structure
`struct V`. The space is initialized to all bits zero. The function
returns either a pointer to the allocated memory or, if the allocation
fails, `NULL`.

## The `realloc` function

``` c
 void * realloc ( void * ptr, size_t size );
```

The `realloc` function changes the size of the object pointed to by
`ptr` to the size specified by `size`. The contents of the object shall
be unchanged up to the lesser of the new and old sizes. If the new size
is larger, the value of the newly allocated portion of the object is
indeterminate. If `ptr` is a null pointer, the `realloc` function
behaves like the `malloc` function for the specified size. Otherwise, if
`ptr` does not match a pointer earlier returned by the `calloc`,
`malloc`, or `realloc` function, or if the space has been deallocated by
a call to the `free` or `realloc` function, the behavior is undefined.
If the space cannot be allocated, the object pointed to by `ptr` is
unchanged. If `size` is zero and `ptr` is not a null pointer, the object
pointed to is freed. The `realloc` function returns either a null
pointer or a pointer to the possibly moved allocated object.

## The `free` function

Memory that has been allocated using `malloc`, `realloc`, or `calloc`
must be released back to the system memory pool once it is no longer
needed. This is done to avoid perpetually allocating more and more
memory, which could result in an eventual memory allocation failure.
Memory that is not released with `free` is however released when the
current program terminates on most operating systems. Calls to `free`
are as in the following example.

``` c
int *myStuff = malloc( 20 * sizeof(int));
if (myStuff != NULL)
{
   /* more statements here */
   /* time to release myStuff */
   free( myStuff );
}
```

### free with recursive data structures

It should be noted that `free` is neither intelligent nor recursive. The
following code that depends on the recursive application of free to the
internal variables of a struct
does not work.

``` c
typedef struct BSTNode
{
   int value;
   struct BSTNode* left;
   struct BSTNode* right;
} BSTNode;

// Later: ...

BSTNode* temp = (BSTNode*) calloc(1, sizeof(BSTNode));
temp->left = (BSTNode*) calloc(1, sizeof(BSTNode));

// Later: ...

free(temp); // WRONG! don't do this!
```

The statement \"`free(temp);`\" will **not** free `temp->left`, causing
a memory leak. The correct way is to define a function that frees
*every* node in the data structure:

``` c
void BSTFree(BSTNode* node){
    if (node != NULL) {
        BSTFree(node->left);
        BSTFree(node->right);
        free(node);
    }
}
```

Because C does not have a garbage collector, C programmers are
responsible for making sure there is a `free()` exactly once for each
time there is a `malloc()`. If a tree has been allocated one node at a
time, then it needs to be freed one node at a time.

### Don\'t free undefined pointers

Furthermore, using `free` when the pointer in question was never
allocated in the first place often crashes or leads to mysterious bugs
further along.

To avoid this problem, always initialize pointers when they are
declared. Either use `malloc` at the point they are declared (as in most
examples in this chapter), or set them to `NULL` when they are declared
(as in the \"delayed allocation\" example in this chapter). [^1]

### Write constructor/destructor functions

One way to get memory initialization and destruction right is to imitate
object-oriented programming. In this paradigm, objects are constructed
after raw memory is allocated for them, live their lives, and when it is
time for them to be destructed, a special function called a destructor
destroys the object\'s innards before the object itself is destroyed.

For example:

``` c
#include <stdlib.h> /* need malloc and friends */

/* this is the type of object we have, with a single int member */
typedef struct WIDGET_T {
  int member;
} WIDGET_T;

/* functions that deal with WIDGET_T */

/* constructor function */
void
WIDGETctor (WIDGET_T *this, int x)
{
  this->member = x;
}

/* destructor function */
void
WIDGETdtor (WIDGET_T *this)
{
  /* In this case, I really don't have to do anything, but
     if WIDGET_T had internal pointers, the objects they point to
     would be destroyed here.  */
  this->member = 0;
}

/* create function - this function returns a new WIDGET_T */
WIDGET_T *
WIDGETcreate (int m)
{
  WIDGET_T *x = 0;

  x = malloc (sizeof (WIDGET_T));
  if (x == 0)
    abort (); /* no memory */
  WIDGETctor (x, m);
  return x;
}

/* destroy function - calls the destructor, then frees the object */
void
WIDGETdestroy (WIDGET_T *this)
{
  WIDGETdtor (this);
  free (this);
}

/* END OF CODE */
```

## References

-   Memory Management

fr:Programmation C/Gestion de la
mémoire

[^1]: \"Bug 478901 \... libpng-1.2.34 and earlier might free undefined
    pointers\"


# C Programming/Error handling

C does not provide direct support for error handling (also known as
exception handling). By convention, the programmer is expected to
prevent errors from occurring in the first place, and test return values
from functions. For example, -1 and NULL are used in several functions
such as socket() (Unix socket programming) or malloc() respectively to
indicate problems that the programmer should be aware about. In a worst
case scenario where there is an unavoidable error and no way to recover
from it, a C programmer usually tries to log the error and
\"gracefully\" terminate the program.

There is an external variable called \"errno\", accessible by the
programs after including \<errno.h\> - that file comes from the
definition of the possible errors that can occur in some Operating
Systems (e.g. Linux - in this case, the definition is in
include/asm-generic/errno.h) when programs ask for resources. Such
variable indexes error descriptions accessible by the function
\'strerror( errno )\'.

The following code tests the return value from the library function
malloc to see if dynamic memory allocation completed properly:

``` c
#include <stdio.h>        /* perror */
#include <errno.h>        /* errno */
#include <stdlib.h>       /* malloc, free, exit */

int main(void)
{

    /* Pointer to char, requesting dynamic allocation of 2,000,000,000
     * storage elements (declared as an integer constant of type
     * unsigned long int). (If your system has less than 2 GB of memory
     * available, then this call to malloc will fail.)
     */
    char *ptr = malloc(2000000000UL);

    if (ptr == NULL) {
        perror("malloc failed");
        /* here you might want to exit the program or compensate
           for that you don't have 2GB available
         */
    } else {
        /* The rest of the code hereafter can assume that 2,000,000,000
         * chars were successfully allocated...
         */
        free(ptr);
    }

    exit(EXIT_SUCCESS); /* exiting program */
}
```

The code snippet above shows the use of the return value of the library
function malloc to check for errors. Many library functions have return
values that flag errors, and thus should be checked by the astute
programmer. In the snippet above, a NULL pointer returned from malloc
signals an error in allocation, so the program exits. In more
complicated implementations, the program might try to handle the error
and try to recover from the failed memory allocation.

## Preventing divide by zero errors

A common pitfall made by C programmers is not checking if a divisor is
zero before a division command. The following code will produce a
runtime error and in most cases, exit.

``` c
int dividend = 50;
int divisor = 0;
int quotient;

quotient = (dividend/divisor); /* This will produce a runtime error! */
```

In ordinary arithmetic division by zero
is undefined. Because of this, you must check or make sure that a
divisor is never zero. Alternatively, for \*nix processes, you can stop
the OS from terminating your process by blocking the SIGFPE signal.

The code below fixes this by checking if the divisor is zero before
dividing.

``` c
#include <stdio.h> /* for fprintf and stderr */
#include <stdlib.h> /* for exit */
int main( void )
{
    int dividend = 50;
    int divisor = 0;
    int quotient;

    if (divisor == 0) {
        /* Example handling of this error. Writing a message to stderr, and
         * exiting with failure.
         */
        fprintf(stderr, "Division by zero! Aborting...\n");
        exit(EXIT_FAILURE); /* indicate failure.*/
    }

    quotient = dividend / divisor;
    exit(EXIT_SUCCESS); /* indicate success.*/
}
```

## Signals

In some cases, the environment may respond to a programming error in C
by raising a signal. Signals are events raised by the host environment
or operating system to indicate that a specific error or critical event
has occurred (e.g. a division by zero, interrupt, and so on.) However,
these signals are not meant to be used as a means of error catching;
they usually indicate a critical event that will interfere with normal
program flow.

To handle signals, a program needs to use the `signal.h` header file. A
signal handler will need to be defined, and the signal() function is
then called to allow the given signal to be handled. Some signals that
are raised to an exception within your code (e.g. a division by zero)
are unlikely to allow your program to recover. These signal handlers
will be required to instead ensure that some resources are properly
cleaned up before the program terminates.

The C Standard Library only defines six signals; Unix systems define 15
more. Each signal has a number, called a signum, associated with it.
Here are a few common ones:

``` c
    #define SIGHUP  1   /* Hangup the process */
    #define SIGINT  2   /* Interrupt the process. C standard */
    #define SIGQUIT 3   /* Quit the process */
    #define SIGILL  4   /* Illegal instruction. C standard.*/
    #define SIGTRAP 5   /* Trace trap, for debugging. C standard.*/
    #define SIGABRT 6   /* Abort. C standard. */
    #define SIGFPE  8   /* Floating Point Error. C standard. */
    #define SIGSEGV 11  /* Memory error. C standard.  */
    #define SIGTERM 15  /* Termination request. C standard. */
```

Signals are handled with the `signal()` function, from the `signal.h`
library. Its syntax is:

``` c
void signal(signal_to_catch, signal_handler)
```

Signals can be raised with `raise()` or `kill()`. `raise()` sends the
signal to the current process; `kill()` sends it to a specific process.

*Note that `signal` is now deprecated in favor of `sigaction()`, due to
a lack of portability between Unix systems and potential for unexpected
behavior. However, as `sigaction()`\'s use is more complicated, we will
stick with `signal()` to illustrate the concept here.*

To understand how signals work, here\'s a simple example:

``` c
#include <stdio.h>
#include <unistd.h> // Unix Standard library, used to import sleep()
#include <stdlib.h>
#include <signal.h>

void handler(int signum) {
   printf("Signal received %d, coming out...\n", signum);
   exit(1);
}

int main () {
   signal(SIGINT, handler); // attaching the handler() function to SIGINT signals; i.e, ctrl+c, keyboard interrupt.

   while(1) {
      printf("Sleeping...\n");
      sleep(1000); // sleep pauses the process for a given number of seconds, or until a signal is received.
   }
   return(0);
}
```

Try compiling and testing this on your machine; after you see
\"Sleeping\...\", send the interrupt signal by pressing `ctrl + c`.

Here\'s a more complex example. This creates a signal handler and raises
the signal:

``` c
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

static void catch_function(int signal) {
    puts("Interactive attention signal caught.");
}

int main(void) {
    if (signal(SIGINT, catch_function) == SIG_ERR) {
        fputs("An error occurred while setting a signal handler.\n", stderr);
        return EXIT_FAILURE;
    }
    puts("Raising the interactive attention signal.");
    if (raise(SIGINT) != 0) {
        fputs("Error raising the signal.\n", stderr);
        return EXIT_FAILURE;
    }
    puts("Exiting.");
    return 0;
}
```

## setjmp

The setjmp function can be
used to emulate the exception handling feature of other programming
languages. The first call to setjmp stores a reference point to the
current execution point, and is valid as long as the function containing
setjmp() doesn\'t return or exit. A call to longjmp causes the execution
to return to the point of the associated setjmp call.

`setjmp` takes a \`jmp_buf\` (a type that will store an execution
context) as an argument, and returns `0` the first time it runs (i.e.,
when it sets the return point). When it runs a second time - when
`longjmp` is called - it then returns the value passed to `longjmp`.

`longjmp` takes a \`jmp_buf\` as an argument (one that\'s already been
passed to `setjmp`), and a value to pass to `setjmp` to return.

``` c
#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>

int main(void) {
   int val;
   jmp_buf environment;

   val = setjmp(environment); // val is set to 0 the first time this is called

   if (val !=0)
   {
      printf("You returned from a longjmp call, return value is %d", val); // now, value is 1, passed from longjmp()
      exit(0);
   }

   puts("Calling longjmp now");
   longjmp(environment, 1);

   return(0);
}
```

Try running this with a compiler on your own machine.

The values of non-volatile variables may be corrupted when setjmp
returns from a longjmp call.

While setjmp() and longjmp() may be used for error handling, it is
generally preferred to use the return value of a function to indicate an
error, if possible. setjmp() and longjmp() are most useful when errors
occur in deeply nested function calls, and it would be tedious to check
return values all the way back to the point you wish to return to.