'Addition of address and integer data type [duplicate]
I wrote the following programme in C++
#include<iostream>
using namespace std ;
int main()
{ int a,i , *p;
string str[4] = {"one","two","three","four"};
p = &a ; // stores address of a into p
*p = 12 ; // puts integer 4 on the adress present in p i.e a = 4
cout<<"Value is:- "<<*(&a + 1)<<endl ; // shows value stored at next address
// working on array
int x= *(&str + 1) - str ; //&str is adress , how can we add integer ?
cout<<"line 1 is:-"<<(&str + 1)<<endl; // LINE 1
cout<<"line 2 is:-"<<(*(&str+1))<<endl; // LINE 2
cout<<"size is :-"<<x;
return 0 ;
}
Below is the output
I came to know that *(&str + 1) is the immediate address after last elements of the the array & also that str stores the address of firt element.
Below are few things which I am unable to understand :-
1.
cout<<"line 1 is:-"<<(&str + 1)<<endl; // LINE 1
cout<<"line 2 is:-"<<*(&str+1)<<endl; // LINE 2
Why both the lines are showing same output ? Line 2 is having "*" operator , so it must point to a particular value stored at the address,Just like *(&a + 1) points to a integer value stored at an address next to &a .
Why & how *(&str+1) showing an address data type value ?
- In this line
int x= *(&str + 1) - str
How difference of two address is stored in a integer data type ?
Solution 1:[1]
In line 1 ,How are we able to add 1 (int type) to &str which is an address data type ?
This is called pointer arithmetic. Pointers are iterators for arrays. If you have an random access iterator (such as a pointer) to an element of a range (an array in this case), and add an integer i to the iterator, the result is an iterator to the ith successive sibling of the previously pointed range element.
Now, &str is not a pointer to an element of an array, but rather a pointer to a singular object (which happens to be an array object). It's well defined to perform pointer arithmetic by adding 1 to such pointer as if it was element of an array containing a single element. The result of such addition is a pointer past the end of the object. Hence, &str and &str+1 can be used as a pair of iterators to a half-open range containing that single object. Indirecting through an iterator past the end of a range will result in undefined behaviour.
Why both the lines are showing same output ?
On the second line, in expression *(&str+1), you indirect through a pointer beyond the pointed object, and the behaviour of the program is undefind.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

