Pointers in C


Pointers in C++

To declare a pointer in C++, use the indirection operator (*) before the identifier:

data_type *pointer_name;  int *i; /* pointer to an int */

To initialize the pointer in C++, you have to use the reference operator (&). Here's how you can declare and automatically initialize a pointer in C++:

int n = 20;  int *i = &n; /* point to "n" */ 

If you want, you can initialize a pointer to point to nothing. In Delphi, you would use nil for this, but in C++, you use the NULL constant (since C++ is case sensitive, always write NULL):

int *p = NULL;

You use pointers in C++ the same way as in Delphi. To access the pointer's address, use the pointer name without additional operators, and to access the value to which it points, write the indirection operator (*) before the pointer's name (see Listing 9-7).

Listing 9-7: Pointer basics

image from book
#include <iostream.h> #include <conio.h> #pragma hdrstop #pragma argsused int main(int argc, char* argv[]) {    int n = 20;    int *i = &n; /* point to "n" */    cout << i << endl;         // display the pointer's address    cout << *i << endl;        // display the value of the n variable    getch();    return 0; }
image from book

void Pointers

Pointers of type void are the C++ equivalent of Delphi's Pointer type, which means that a void pointer is untyped and can be used to point to a variable of any data type. The void pointer in C++ has the same "limitation" the Pointer type in Delphi has: To access the value to which it points, you must first type- cast it to a typed pointer type and dereference it. To do this, use the following syntax:

*(typed_pointer)void_pointer_name

Listing 9-8 illustrates how to work with void pointers.

Listing 9-8: Void pointers

image from book
#include <iostream.h> #include <conio.h> #pragma hdrstop #pragma argsused int main(int argc, char* argv[]) {    int n = 20;    char c = 'A';    float f = 1.45;    void *ptr = &n;                   // declare the pointer and point it to "n"    cout << *(int *)ptr << endl;    ptr = &c;                         // point to the "c" variable"    cout << *(char *)ptr << endl;     // display A    ptr = &f;                         // point to "f"    cout << *(float *)ptr << endl;    getch();    return 0; }
image from book

Accessing Array Elements

To access an array through a pointer, you need to make the pointer point to an element in the array, usually the first one. To get the address of the first element in an array, simply assign the array's name to the pointer:

pointer = array;

To move to another element in an array, use the ++ or -- operators:

pointer++;  // move to the next element

The following listing illustrates how to access array elements through a pointer.

Listing 9-9: Accessing array elements through a pointer

image from book
#include <iostream.h> #include <conio.h> #pragma hdrstop #pragma argsused int main(int argc, char* argv[]) {    int arr[5] = {1, 2, 3, 4, 5};    int *p;    p = arr;                   // point to the first element in the array    cout << *p << endl;    p = &arr[0];               // this is the same as p = arr;    cout << *p << endl;    p++;                      // move to the 2nd element    cout << *p << endl;    p +=2;                    // move to the 4th element    cout << *p << endl;    getch();    return 0; }
image from book

Pointers to Structures

When you declare a pointer to a structure, you can no longer access the fields using the simple dot syntax (the direct member selector). To access fields in a structure pointed to by a pointer, you have to write this:

(*pointer_name).field_name

Although you can use the above syntax to access fields in pointers to structures, it is much better to use the indirect member selector, or the -> operator, because it is used in object-oriented programming to access object fields:

pointer_name->field_name

The following listing shows how to access fields in a structure through a pointer. The example illustrates both ways of accessing fields indirectly.

Listing 9-10: Accessing structure fields through a pointer

image from book
#include <iostream.h> #include <conio.h> #include <string.h> #pragma hdrstop struct TBook {    char Title[50];    int PageCount;    char Authors[4][40]; }; #pragma argsused int main(int argc, char* argv[]) {    TBook book;    TBook* bookPtr = &book;    // access the book structure through the pointer    strcpy((*bookPtr).Title, "The ANSI C Programming Language");    // display data by accessing the book structure directly    cout << "Title: " << book.Title << endl;    strcpy(bookPtr->Authors[0], "Brian W. Kernighan");    cout <<"Author: " << book.Authors[0] << endl;    strcpy(bookPtr->Authors[1], "Dennis M. Ritchie");    cout <<"Author: " << book.Authors[1] << endl;     (*bookPtr).PageCount = 238;    cout << "Page Count: " << book.PageCount << endl;    getch();    return 0; }
image from book

Dynamic Variables

You create and use dynamic variables the same way in Delphi and C++; the only difference lies in syntax.

To create a new dynamic variable in C++, you need to declare a pointer and allocate it on the heap using the new operator:

data_type *pointer_name = new data_type;  int *p = new int;

You can also automatically initialize a dynamic variable by including a pair of parentheses containing the initial value of the variable:

data_type *pointer_name = new data_type(initial_value);  int *p = new int(1001);

When you're done with the dynamic variable, you must release it from memory if you don't want to leak memory. To remove a dynamic variable from memory, use the delete operator:

delete pointer_name;  delete p;

The short example in Listing 9-11 illustrates how to use a dynamic variable.

Listing 9-11: Dynamic variables in C++

image from book
#include <iostream.h> #include <conio.h> #pragma hdrstop #pragma argsused int main(int argc, char* argv[]) {    int *p = new int(1001);      // create & initialize the dynamic var    cout << *p << endl;          // use the variable    delete p;                    // remove the var from memory    getch();    return 0; }
image from book

Dynamic Arrays

The new operator is used to create both dynamic variables and dynamic arrays. When you want to create a dynamic array, use the following syntax:

data_type *array_name = new data_type[num_of_elements];

Removing a dynamic variable and a dynamic array from memory is done using the delete operator. The only difference is that when you want to delete an array, you have to use the delete [] syntax:

int *dyn_var = new int; int *dyn_array = new int[20]; delete dyn_var;                // delete one variable delete [] dyn_array;           // delete an entire array

Strings (Dynamic Character Arrays)

Now that you know more about pointers, you can start declaring strings using the following syntax:

char * string_name; 

The difference between char[] and char* is that a char[] string is stored on the stack and the char* string is stored in the heap. Actually, the char* pointer (4 bytes) is stored on the stack and the string's data is stored on the heap.



Inside Delphi 2006
Inside Delphi 2006 (Wordware Delphi Developers Library)
ISBN: 1598220039
EAN: 2147483647
Year: 2004
Pages: 212
Authors: Ivan Hladni

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net