Monday, January 28, 2008

More C++ Pointers

When you perform pointer arithmetic, you move the pointer to the next or previous element of the array. When you say ptr++ where ptr is an integer pointer, it is equivalent to ptr = ptr + 4 (mathematically) assuming integer is of 4 bytes.

Do not do math on pointers that does not point to array. If one keeps this in mind, then you would probably prevent most of the problems.

The following code snippet is perfectly legal:

*ptr = array;
ptr = ptr+2;

Consider the following declaration:


In the above declaration, numbers is of type int const*. This implies that numbers even though is a pointer, is a constant pointer and it cannot appear on the left side of an expression(as a pointer).

int *numbers;

In the above shown declaration,numbers is of type int*. It can still point to an array of itegers and you can actually do a math and can appear on the left side of an expression. So the statement numbers++ in this case is perfectly legal while in the previous case; it is not legal.

Technorati Tags: ,

No comments: