Understanding pointers in C/C++

(0 votes, average 0 out of 5)

Please Note: This article assumes a familiarity with C and general programming concepts including structs, variables, integer data types, and arrays. For an introduction to C, please read this Cprogramming.com tutorial.

One of the most difficult concepts to grasp when learning C/C++ is pointers. They are similar to pointer variables in more modern languages like Java or C#, but their usage is more subtle. A pointer is just a variable which holds the address of another variable in memory. For example, consider the integer variable x and a pointer variable to x called px:

int x = 42;
int *px = &x;	// declare a pointer with the * character next to the variable name

Here's how these variables would look in memory, with the value of px being the address where x is located. The value of x is 42, the integer value it was given upon initialization.

pointer-memory

As you can see from the above declaration, there are a couple important operators that must be used when dealing with pointers:

  • * is called the dereferencing operator. It basically says "do this to whatever the pointer points to". It is used when declaring a pointer or operating on the variable that a pointer points to.
  • & is called the address operator. It says "get the literal memory address of this variable". It is used when declaring a pointer or when passing a pointer to a function (see below).

Pointers generally cannot be operated on like other variables, meaning you can't multiply or divide pointers. However, you can add an integer value to a pointer. Here's an example of this in use with an array:

 

1
2
3
4
5
6
7
8
9
10
#include <stdlib.h>
#include <stdio.h>
 
void main() {
  int myarray[6];             // declare the array
  int *ptr;                   // declare the pointer
  ptr = myarray;              // tell the pointer to point to the array
  *(ptr + 1) = 100;           // equivalent to myarray[1] = 100;
  printf("%i\n", myarray[1]); // prints "100"
}

 

 

Pointers can also be used with structs. For example, we have a struct which represents a list. After declaring a pointer to the head of the list, we can refer to members of the struct using the -> notation with the pointer:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdlib.h>
#include <stdio.h>
 
void main() {
  typedef struct list {
    int value;
    struct list *next;
  } list;
 
  list mylist;            // declare the list
  list *head;             // declare the head pointer
  head = &mylist;         // initialize the head pointer
 
  head->value = 2;        // equivalent to (*head).value = 2;
  printf("%i\n", head->value); // prints "2"
}

 

 

Functions in C make a copy of variables passed as arguments, thus not changing the original variables. In order to have a function operate on a variable, it must be passed as a pointer, like below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdlib.h>
#include <stdio.h>
 
void numChanger(int *num) {
  *num = 42;			// change the value to 42
}
 
void main() {
  int mynumber = 2;		// initialize the number to 2
  printf("%i\n", mynumber);	// print the number, "2"
 
  int *myptr = &mynumber;	// initialize the pointer
 
  numChanger(myptr);		// call the function, passing the pointer
 
  printf("%i\n", *myptr);	// print the number, now "42"
}

 

For more details on the C and C++ programming languages, please refer to the books listed below in the citation section.

 

Partner Links:
 
Related Articles

» Conditional (If-Else) Statements in Python

Below is a quick example of how to use an if statement in python: 12345if x==3: print "We are inside an if statement" x = x + 1print "we are no longer in an if statement" Note that unlike most languages, no parentheses are needed, although including parentheses does not violate python syntax.  Anything indented after the if statement is included in the execution if the if statement evaluates to true.  The scope is closed once indentation returns to the indent location of the...

» Java - Reading and writing a properties file

A properties file in Java can be very useful when you start to notice that there are many locations in your code where you are either hard coding values, many constants, or using enums. Instead of including these values directly in your code, you can refactor them out to a properties file to separate responsibilities. Instead of potentially specifying values throughout many classes or programs, all values can be condensed into one or more properties files as need.An example of a properties file...

» Oracle 9.2.0 Error: System.Data.OracleClient requires Oracle client software version 8.1.7

ProblemWhen using a version of Oracle 9.2.0 in ASP.NET, attempting to access a site which uses System.Data.OracleClient may give an error with the following exception:  System.Data.OracleClient requires Oracle client software version 8.1.7 or greater This is a common error when using ASP.NET with Oracle -- it is in fact a bug in the default Oracle 9.2.0 installation permissions.  To fix the error, follow the following solution steps (taken from cited source): Log on to...