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

» For Loops in Python

For loops in Python are a bit different than most languages.  You may not iterate over some integer and increment as you go.  Rather, python uses for loops to iterate over lists or strings (represented as lists).  Python also does not use brackets to determine scope, but rather indentation.  Example below.  123>>> x = [1, 2, 3]>>> for value in x: #begin for loop, note the colon>>> print x #part of the loop, indented in In some cases, you want to know the where in...

» How to Send Mail in PHP

The BasicsPHP provides a handy function for mailing from a server.  On a basic level, all you need to do is call the function mail with three parameters, which has the following syntax.bool (string $to, string $subject, string $message [, string $headers][, string $additonal_params]]) These parameters are pretty straight forward.  Below is an example of how to send a very simple email message with no headers.1234$to = "example@wisc.edu";$subject = "This is an example email.";$message...

» 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...