Topic : Programming in C/C++
Author : Alexander Allain
Page : << Previous 4  Next >>
Go to page :


It is possible to have it give the actual address to another variable, or to pass it into a function. To do so, simply use the name of the pointer without the *. However, to access the actual memory location, use the *. The technical name for this doing this is dereferencing.

In order to have a pointer actually point to another variable it is necessary to have the memory address of that variable also. To get the memory address of the variable, put the & sign in front of the variable name. This makes it give its address. This is called the reference operator, because it returns the memory address.
For example:

#include <iostream.h>
int main()
{
int x;              //A normal integer
int *pointer;    //A pointer to an integer
pointer=&x;      //Read it, "pointer equals the address of x"
cin>>x;          //Reads in x    
cout<<*pointer; //Note the use of the * to output the actual number stored in x
return 0;
}
  

The cout outputs the value in x. Why is that? Well, look at the code. The integer is called x. A pointer to an integer is then defined as "pointer". Then it stores the memory location of x in pointer by using the ampersand (&) symbol. If you wish, you can think of it as if the jar that had the integer had a ampersand in it then it would output its name (in pointers, the memory address) Then the user inputs the value for x. Then the cout uses the * to put the value stored in the memory location of pointer. If the jar with the name of the other jar in it had a * in front of it would give the value stored in the jar with the same name as the one in the jar with the name. It is not too hard, the * gives the value in the location. The unastricked gives the memory location.

Notice that in the above example, pointer is initialized to point to a specific memory address before it is used. If this was not the case, it could be pointing to anything. This can lead to extremely unpleasant consequences to the computer. You should always initialize pointers before you use them.

It is also possible to initialize pointers using free memory. This allows dynamic allocation of array memory. It is most useful for setting up structures called linked lists. This difficult topic is too complex for this text. An understanding of the keywords new and delete will, however, be tremendously helpful in the future.

The keyword new is used to initialize pointers with memory from free store (a section of memory available to all programs). The syntax looks like the example:

Example:
int *ptr = new int;

It initializes ptr to point to a memory address of size int (because variables have different sizes, number of bytes, this is necessary). The memory that is pointed to becomes unavailable to other programs. This means that the careful coder will free this memory at the end of its usage.

The delete operator frees up the memory allocated through new. To do so, the syntax is as in the example.

Example:
delete ptr;

After deleting a pointer, it is a good idea to reset it to point to NULL. NULL is a standard compiler-defined statement that sets the pointer to point to, literally, nothing. By doing this, you minimize the potential for doing something foolish with the pointer.

The final implication of NULL is that if there is no more free memory, it is possible for the ptr after being "new"-ed to point to NULL. Therefore, it is good programming practice to check to ensure that the pointer points to something before using it. Obviously, the program is unlikely to work without this check.



Lesson 7: Structures


Before discussing classes, this lesson will be an introduction to data structures similar to classes. Structures are a way of storing many different variables of different types under the same name. This makes it a more modular program, which is easier to modify because its design makes things more compact. It is also useful for databases.

The format for declaring a structure(in C++, it is different in C) is
struct NAME
{
  VARIABLES;
};

Where NAME is the name of the entire type of structure. To actually create a single structure the syntax is NAME name_of_single_structure; To access a variable of the structure it goes name_of_single_structure.name_of_variable;

For example:
struct example
{
  int x;
};

example an_example;  //Treating it like a normal variable type
an_example.x=33;     //How to access it


Here is an example program:
struct database
{
  int id_number;
  int age;
  float salary;
};
int main()
{
  database employee;  //There is now an employee variable that has modifiable
       //variables inside it.
  employee.age=22;
  employee.id_number=1;
  employee.salary=12000.21;
  return 0;
}


The struct database declares that database has three variables in it, age, id_number, and salary.

You can use database like a variable type like int. You can create an employee with the database type as I did above. Then, to modify it you call everything with the 'employee.' in front of it. You can also return structures from functions by defining their return type as a structure type. Example:

struct database fn();

I suppose I should explain unions a little bit. They are like structures except that all the variables share the same memory. When a union is declared the compiler allocates enough memory for the largest data-type in the union. Its like a giant storage chest where you can store one large item, or a bunch of small items, but never the both at the same time.

The '.' operator is used to access different variables inside a union also.

As a final note, if you wish to have a pointer to a structure, to actually access the information stored inside the structure that is pointed to, you use the -> operator in place of the . operator.

A quick example:
#include <iostream.h>
struct xampl
{
  int x;
};

int main()
{  
  xampl structure;
  xampl *ptr;
  structure.x=12;
  ptr=&structure; //Yes, you need the & when dealing with structures
      //and using pointers to them
  cout<<ptr->x;  //The -> acts somewhat like the * when used with pointers
   //It says, get whatever is at that memory address
   //Not "get what that memory address is"
  return 0;
}



Lesson 8: Array basics


Arrays are useful critters because they can be used in many ways. For example, a tic-tac-toe board can be held in an array. Arrays are essentially a way to store many values under the same name. You can make an array out of any data-type including structures and classes.

Think about arrays like this:

[][][][][][]

Each of the bracket pairs is a slot(element) in the array, and you can put information into each one of them. It is almost like having a group of variables side by side.
Lets look at the syntax for declaring an array.

int examplearray[100]; //This declares an array

This would make an integer array with 100 slots, or places to store values(also called elements). To access a specific part element of the array, you merely put the array name and, in brackets, an index number. This corresponds to a specific element of the array. The one trick is that the first index number, and thus the first element, is zero, and the last is the number of elements minus one. 0-99 in a 100 element array, for example.

What can you do with this simple knowledge? Lets say you want to store a string, because C++ has no built-in datatype for strings, at least in DOS, you can make an array of characters.
For example:

char astring[100];

will allow you to declare a char array of 100 elements, or slots. Then you can receive input into it it from the user, and if the user types in a long string, it will go in the array. The neat thing is that it is very easy to work with strings in this way, and there is even a header file called string.h. There is another lesson on the uses of string.h, so its not necessary to discuss here.
The most useful aspect of arrays is multidimensional arrays.

How I think about multi-dimensional arrays.
[][][][][]
[][][][][]
[][][][][]
[][][][][]
[][][][][]

This is a graphic of what a two-dimensional array looks like when I visualize it.

For example:

int twodimensionalarray[8][8];

declares an array that has two dimensions. Think of it as a chessboard. You can easily use this to store information about some kind of game or to write something like tic-tac-toe. To access it, all you need are two variables, one that goes in the first slot and one that goes in the second slot. You can even make a three dimensional

Page : << Previous 4  Next >>