pointer arithmetic
The C++ language allows you to perform addition or subtraction of integers on pointers. Yeahptr
points to an integer,dot + 1
is the address of the next integer in memory after ptr.ptr - 1
is the address of the previous integer beforeptr
.
watch thatdot + 1
do not return thememory addressafterptr
, but the memory address of thenext type objectthatptr
point to. Yeahptr
points to an integer (assuming 4 bytes),dot + 3
means 3 integers (12 bytes) afterptr
. Septr
points to aCharacters
, which is always 1 byte,dot + 3
means 3 characters (3 bytes) after ptr.
When calculating the result of a pointer arithmetic expression, the compiler always multiplies the integer operand by the size of the object pointed to. is calledscale.
Consider the following program:
#include <iostream>int main(){ int value{ 7 }; int* ptr{ &value }; std::cout << ptr << '\n'; std::cout << ptr+1 << '\n'; std::cout << ptr+2 << '\n'; std::cout << ptr+3 << '\n'; returns 0;}
On the author's machine, this output:
0012FF7C0012FF800012FF840012FF88
As you can see, each of these addresses differs by 4 (7C + 4 = 80 in hexadecimal). This is because an integer is 4 bytes long on the author's machine.
The same program usingshort
instead ofAnd t
:
#include <iostream>int main(){ short value{ 7 }; short* ptr{ &value }; std::cout << ptr << '\n'; std::cout << ptr+1 << '\n'; std::cout << ptr+2 << '\n'; std::cout << ptr+3 << '\n'; returns 0;}
On the author's machine, this output:
0012FF7C0012FF7E0012FF800012FF82
Since a short is 2 bytes, each address differs by 2.
The matrices are arranged sequentially in memory.
Using the address operator (&), we can determine that the arrays are arranged sequentially in memory. That is, the elements 0, 1, 2,... are all adjacent to each other, in order.
#include <iostream>int main(){ int array[]{ 9, 7, 5, 3, 1 }; std::cout << "Element 0 is at address: " << &array[0] << '\n'; std::cout << "Element 1 is at address: " << &array[1] << '\n'; std::cout << "Element 2 is at address: " << &array[2] << '\n'; std::cout << "Element 3 is at address: " << &array[3] << '\n'; returns 0;}
This is printed on the author's machine:
Element 0 is at address: 0041FE9CElement 1 is at address: 0041FEA0Element 2 is at address: 0041FEA4Element 3 is at address: 0041FEA8
Note that each of these memory addresses is separated by 4 bytes, which is the size of an integer on the author's machine.
Pointer Arithmetic, Arrays, and the Magic Behind Indexing
In the previous section, you learned that arrays are arranged in memory sequentially.
In the previous lesson, you learned that a fixed array can decay to a pointer that points to the first element (element 0) of the array.
Also in the previous section, you learned that adding 1 to a pointer returns the memory address of the next object of that type in memory.
Therefore, we can conclude that adding 1 to an array must point to the second element (element 1) of the array. Experimentally we can verify that this is true:
#include <iostream>int main(){ int array[]{ 9, 7, 5, 3, 1 }; std::cout << &array[1] << '\n'; // print the memory address of element 1 of the array std::cout << array+1 << '\n'; // print the memory address of the array pointer + 1 std::cout << array[1] << '\n'; // prints 7 std::cout << *(array+1) << '\n'; // prints 7 (note the required parentheses here) returns 0;}
Note that when indirecting through the result of pointer arithmetic, the parentheses are necessary to ensure correct operator precedence, since the * operator has higher precedence than the + operator.
This is printed on the author's machine:
0017FB800017FB8077
It turns out that when the compiler sees the subscript operator ([]), it actually translates it into pointer addition and indirection. generalizing,array[n]
is the same as*(matrix + n)
, where n is an integer. The subscript operator [] is there both to look good and to be easier to use (so you don't have to remember the parentheses).
Use a pointer to traverse an array
We can use a pointer and pointer arithmetic to loop through an array. While it's not usually done this way (using subscripts is often easier to read and less error prone), the following example shows that it is possible:
#include <iostream>#include <iterator> // for std::sizebool isVowel(char ch){ switch (ch) { case 'A': case 'a': case 'E': case 'e': case '. I': case 'i': case 'O': case 'o': case 'U': case 'u': return true; pattern: return false; }}int main(){ charactername[]{ "Mollie" }; int arrayLength{ static_cast<int>(std::size(name)) }; int numVogais{ 0 }; for (char* ptr{ name }; ptr != (name + arrayLength); ++ptr) { if (isVowel(*ptr)) { ++numVowels; } } std::cout << name << " tem " << numVogais << " vogais.\n"; return 0;}
How does it work? This program uses a pointer to loop through each element of an array. Remember that arrays decay into pointers to the first element of the array. So when bootingptr
comname
,ptr
will point to the first element of the array. indirection throughptr
is executed for each element when we callis Vogal(*ptr)
, and if the element is a vowel,numVogais
is increased. The for loop then uses the ++ operator to advance the pointer to the next character in the array. The for loop ends when all the characters have been examined.
The above program produces the result:
mollie has 3 vowels
Since element counting is common, the algorithm library providesstd::count_if
, which counts the elements that satisfy a condition. We can replace thefor
-loop with a call tostd::count_if
.
#include <algorithm>#include <iostream>#include <iterator> // for std::begin and std::endbool isVowel(char ch){ switch (ch) { case 'A': case 'a': case ' E': case 'e': case 'I': case 'i': case 'O': case 'o': case 'U': case 'u': return true; default: returns false; }}int main(){ character name[]{ "Mollie" }; // loop through all name elements and count how many calls to isVowel return true auto numVowels{ std::count_if(std::begin(name), std::end(name), isVowel) }; std::cout << name << " has " << numVowels << " vowels.\n"; returns 0;}
standard::start
returns an iterator (pointer) to the first element, whilepattern::end
returns an iterator for the element that would be one after the last. The iterator returned bypattern::end
it's only used as a placeholder, accessing it causes undefined behavior as it doesn't point to an actual element.
standard::start
mipattern::end
only works on arrays with a known size. If the array has been reduced to a pointer, we can calculate the start and end manually.
// nameLength is the number of elements in the array.std::count_if(name, name + nameLength, isVowel) // Don't do this. Accessing invalid indexes causes undefined behavior. // std::count_if(name, &name[nameLength], isVowel)
Notice that we are calculatingname + name length
, Noname + name length - 1
, because we don't want the last element, but the pseudo-element one after the last.
Calculating the start and end of an array like this works for all algorithms that need a start and end argument.
time to ask
Question 1
Why does the following code work?
#include <iostream>int main(){int arr[]{ 1, 2, 3 };std::cout << 2[arr] << '\n';return 0;}
show solution
Question 2
Write a function calledfindValue
which takes a pointer to the beginning and a pointer to the end (1 element after the last) of an array, as well as a value. The function should search for the given value and return a pointer to the first element with that value, or the final pointer if no element is found. The following program should be executed:
#include <iostream>#include <iterator>// ...int main(){ int arr[]{ 2, 5, 4, 10, 8, 20, 16, 40 }; // Find the first element with value 20. int* found{ findValue(std::begin(arr), std::end(arr), 20) }; // If an element with value 20 was found, print it. if (found != std::end(arr)) { std::cout << *found << '\n'; } returns 0;}
Advice
standard::start
mipattern::end
return oneAnd t*
. the call tofindValue
It is equivalent to
int* encontrado{ findValue(arr, arr + std::size(arr), 20) };
show solution
FAQs
Can you index a pointer in C++? ›
The C++ language allows you to perform integer addition or subtraction operations on pointers. If ptr points to an integer, ptr + 1 is the address of the next integer in memory after ptr.
Should you prefer pointer arithmetic or indexes in your code? ›Pointer arithmetic is actually about 30% faster than using array indexes.
What is pointer arithmetic in C++? ›Pointer Arithmetic in C++:
These are addition and subtraction operations. A pointer arithmetic in C++ may be incremented or decremented. It means that we can add or subtract integer value to and from the pointer. Similarly, a pointer arithmetic can be subtracted( or added) from another.
Not only can a pointer store the address of a single variable, it can also store the address of cells of an array. Consider this example: int *ptr; int arr[5]; // store the address of the first // element of arr in ptr ptr = arr; Here, ptr is a pointer variable while arr is an int array.
Can you index arrays in C++? ›An array is a collection of elements of the same type placed in contiguous memory locations that can be individually referenced by using an index to a unique identifier.
Why pointers are not used in C++? ›It is best to avoid using pointers in C++ as much as possible. The use of pointers can lead to confusion of ownership which can directly or indirectly lead to memory leaks. Even if object ownership is well managed simple (and difficult to find) bugs can also lead to memory leaks.
Is pointer arithmetic faster than indexing? ›Sure pointers will be faster. But we need to remember 3 important things about when we wanna discuss pointer vs indexes and optimization. 1)Generally the compiler "read"your code and make a lot o optimization. 2) This optimizations with the modern CPU's speed will make you won't notice any difference.
Which is faster pointer or array? ›So there will be time delay of use arrays rather than pointers but that time delay is negligible.
Can indexes hurt performance? ›The downside to adding indexes to a table is that they affect the performance of writes. Moreover, improperly created indexes can even adversely affect SELECT queries! Any table configuration where performance suffers due to excessive, improper, or missing indexes is considered to be poor indexing.
Are ++* ptr and * ptr ++ same? ›3) Are the expression ++*ptr and *ptr++ are same? The correct option is (b). Explanation: ++*ptr increments the value pointed by ptr and*ptr++ increments the pointer not the value.
What are the 5 basic arithmetic operators in C++? ›
C++ uses operators to do arithmetic. It provides operators for five basic arithmetic calculations: addition, subtraction, multiplication, division, and taking the modulus.
How do you write arithmetic in C++? ›Arithmetic Operators in C++ are used to perform arithmetic or mathematical operations on the operands. For example, '+' is used for addition, '–' is used for subtraction, '*' is used for multiplication, etc.
What are the 4 types of arrays in C++? ›- One-dimensional array.
- Two-dimensional array.
- Multidimensional array.
Array in C is used to store elements of same types whereas Pointers are address varibles which stores the address of a variable. Now array variable is also having a address which can be pointed by a pointer and array can be navigated using pointer.
How many types of pointers are there in C++? ›There are majorly four types of pointers, they are: Null Pointer. Void Pointer. Wild Pointer.
Why do we use auto in C++? ›The auto keyword is a simple way to declare a variable that has a complicated type. For example, you can use auto to declare a variable where the initialization expression involves templates, pointers to functions, or pointers to members.
Does C++ index from 1 or 0? ›Do you know why the C++ array is indexed from zero and not one? This arithmetic operation only has + and * , so if the size of an array is n, then the starting index formula will execute slower due to the one extra operation overhead. This will, therefore, affect the time taken by the program for larger values of n.
Can you do array size () in C++? ›size() function of array class in C++ is used to determine the list/container size. Array size() C++ function works only with the arrays that are defined using the std::array declaration syntax. Array size c++ function does not take any arguments.
Are pointers hard in C++? ›However, "pointer" is also the most complex and difficult feature in C/C++ language. Pointers are extremely powerful because they allows you to access addresses and manipulate their contents. But they are also extremely complex to handle. Using them correctly, they could greatly improve the efficiency and performance.
What can be used instead of pointers? ›Java uses the (safer) idea of references instead of pointers.
In which language pointer is not allowed? ›
Java doesn't have pointers; Java has references.
Do pointers make code faster? ›Execution time is also faster when using pointers. Memory is accessed more efficiently. They can also be used to access elements of arrays and structures and passing arguments to functions by reference instead of by value.
Why is pointer arithmetic useful? ›Using pointer arithmetic ++ as an iterator:
Incrementing pointers with ++, and decrementing with -- is useful when iterating over each element in an array of elements. It is cleaner than using a separate variable used to keep track of the offset.
Indexes increase the amount of data that needs to be logged and written to a database. Indexes reduce write performance.
Is anything faster than C++? ›Python 3.14 Will be Faster than C++ | by Dennis Bakhuis | Towards Data Science.
Is Visual C++ faster than C#? ›C++ code is much faster than C# code, which makes it a better solution for applications where performance is important. For instance, your network analysis software might need some C++ code, but performance is probably not a huge issue for a standard word processing application coded in C#.
Is it better to use array or vector C++? ›Vector occupies more memory. Array is memory efficient data structure. Vector takes more time in accessing elements. Array access elements in constant time irrespective of their location as elements are arranged in a contiguous memory allocation.
When should you avoid indexing? ›- Indexes should not be used on small tables.
- Indexes should not be used on columns that return a high percentage of data rows when used as a filter condition in a query's WHERE clause. ...
- Tables that have frequent, large batch update jobs run can be indexed.
The overall point, however, is how to create the right indexes. To start, I'd say that most tables should have fewer than 15 indexes. In many cases, tables that focus on transaction processing (OLTP) might be in the single digits, whereas tables that are used more for decision support might be well into double digits.
When should indexes be avoided? ›- Indexes should not be used on small tables.
- Tables that have frequent, large batch updates or insert operations.
- Indexes should not be used on columns that contain a high number of NULL values.
- Columns that are frequently manipulated should not be indexed.
Can you access a pointer like an array? ›
So the upshot of that is yes, you can use the [] subscript operator on a pointer expression as well as an array expression. Pointers don't have to be represented as integers - on some older segmented architectures, they were represented as a pair of values (page number and offset).
Can a pointer point to an array? ›C. In this program, we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a pointer that can point to whole array instead of only one element of the array. This pointer is useful when talking about multidimensional arrays.
Can you have a pointer to an array? ›As an alternative to using the traditional array index notation, you can also use a pointer to access and interact with the elements in an array. The process begins by making a copy of the pointer that points to the array: int *ptr = A; // ptr now also points to the start of the array.
How do you declare a pointer to an array in C++? ›An array of pointers is an array that consists of variables of pointer type, which means that the variable is a pointer addressing to some other element. Suppose we create an array of pointer holding 5 integer pointers; then its declaration would look like: int *ptr[5]; // array of 5 integer pointer.
What does * arr means in C++? ›This defines an array of pointer to int , with its number of elements being determined by the number of elements in its initialiser.
Which is better to use pointer or array? ›Array in C is used to store elements of same types whereas Pointers are address varibles which stores the address of a variable. Now array variable is also having a address which can be pointed by a pointer and array can be navigated using pointer.
Why pointer is faster than array? ›Originally Answered: why is pointer indexing faster than array indexing? While doing something with pointer you see essentially accessing memory directly.. In case with arrays, the index is processed and effective addresses are calculated!
What is the pointer to array of 10 integers? ›int (*ptr)[10]; Here ptr is pointer that can point to an array of 10 integers. Since subscript have higher precedence than indirection, it is necessary to enclose the indirection operator and pointer name inside parentheses. Here the type of ptr is 'pointer to an array of 10 integers'.
Is an array in C++ a pointer? ›An array is considered to be the same thing as a pointer to the first item in the array. That rule has several consequences. An array of integers has type int*. C++ separates the issue of allocating an array from the issue of using an array.
What is the relationship between pointer and array in C++? ›An array is represented by a variable that is associated with the address of its first storage location. A pointer is also the address of a storage location with a defined type, so D permits the use of the array [ ] index notation with both pointer variables and array variables.
What is pointer array example? ›
Pointers to an array points the address of memory block of an array variable. The following is the syntax of array pointers. datatype *variable_name[size]; Here, datatype − The datatype of variable like int, char, float etc.
How to create dynamic array of pointers of size 10 using new in C++? ›Solutions for How to create a dynamic array of pointers (to integers) of size 10 using new in C++? Here, one can create a non-dynamic array using int *arr[10]a)int *arr = new int *[10];b)int **arr = new int *[10];c)int *arr = new int [10];d)Not PossibleCorrect answer is option 'B'.
What is the size of pointer array in C++? ›Difference between pointer and array in C++?
The pointer ptr, and all pointers, are 8 bytes, because they hold addresses, which are 8 bytes, or 64 bits. Assigning any address to an array variable is not allowed.
You need to initialize a pointer by assigning it a valid address. This is normally done via the address-of operator (&). The address-of operator (&) operates on a variable, and returns the address of the variable. For example, if number is an int variable, &number returns the address of the variable number.