TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
 Specialized Dev Zones Research Center eBook Library .NET Java C++ Web Dev Architecture Database Security Open Source Enterprise Mobile Special Reports 10-Minute Solutions DevXtra Blogs Slideshow

 Home » Tip Bank » C++ » Pointer Arithmetic
Language: C++
Expertise: Beginner
May 26, 1998

### WEBINAR:On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning

# Pointers

Question:
On a test in college an instructor asked if it was possible to multiply and divide pointers. In the book we are using it says nothing about it, and I was just wondering if you could.

Absolutely. A pointer is just an integer. Although it refers to a location in memory, you can perform operations on a pointer just like you can with any other integer.

You must, of course, be careful because when you use a pointer, you must be certain it points to a valid memory address (generally, this means to memory that your application owns).

Normally, C makes it easy to compute addresses without multiplying and dividing the actual pointer. For example, say you have a pointer to an integer array and you want to figure out the address of an element whose position is equal to x * y.

```*p += (x * y)
```
Here, I've used standard integers (assuming x and y are integers) and simply added the result to a pointer. This is much more common, because we usually rely on the operating system to determine where our memory objects are located. By simply adding to an existing address, we are adding to an address we assume is safe.

It is also important to note that, while each integer uses 4 bytes (in 32-bit C), we didn't need to multiply by 4. This is because C does this for us automatically. Generally, whenever C performs math on a pointer, it automatically multiplies numbers by the number of bytes used by the data type being pointed to.

DevX Pro

 Submit a Tip Browse "C++" Tips Browse All Tips
Comment and Contribute

(Maximum characters: 1200). You have 1200 characters left.

Thanks for your registration, follow us on our social networks to keep up-to-date