Pointers

The use of pointers is very important in C and an essential concept to grasp. My code below with comments helps to explain the fundamentals of declaring integers, pointers and assigning valuables through pointers and passing pointers to functions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <stdio.h>

// Declaration of function

void myFunction(int *ptr, int *ptr2);

int main(int argc, const char * argv[])
{
// Declare two variables

int a=0;
int b=0;

// Declare two pointers

int *ptr;
int *ptr2;

// Point the pointers at the variables

ptr = &a;
ptr2 = &b;

// Call the function and pass the pointers to it

myFunction(ptr, ptr2);

// Print the values assigned by the function

printf("Hello, World! %d %d\n", *ptr2, *ptr);
return 0;
}

void myFunction(int *pointer1, int *pointer2)
{
// Assign values to the variables pointed at
// by the pointers passed to this function
// Note the pointers passed (ptr and ptr2) don't
// have to be the same name as the pointers in
// function, just the same type. In this case ints.

*pointer1 = 8;
*pointer2 = 12;
}

I have written a more in depth post on pointers as it is such an important topic. For this later post please see here

^