devxlogo

Pointers

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.

Answer:
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.

See also  How to Block Websites During Certain Hours on a Mac Computer
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist