C++ pointer . I want to know about the logic - c++

i have a question on pointer concept which i could not find a logical answer to
#include<conio.h>
#include<iostream.h>
void main()
{
int arr[10];
clrscr();
cout<<*arr+5 - *arr+3;
getch();
}
even if i assign arr[0]=10; (or any other value)
the compiler gives answer 8 but how . I can not see(understand) how operator precedence and associativity does solve it.
I will be grateful to you.

Because of *arr - *arr is 0 and 5 + 3 is 8.
The result you may be expecting is the result of:
cout<<(*arr+5) - (*arr+3);

The compiler gives answer 8 because that operation is simply equivalent to: (*arr - *arr) + 5 + 3 = 8. If you want to add the scalar to the pointer and then get the referenced value, you have to use parentheses *(arr+5).

If you look at the precedence table, for example here:
http://en.cppreference.com/w/cpp/language/operator_precedence
then you'll notice that the dereference operator (*) has higher priority than addition/subtraction (+/-) operators (they are in group no. 3 and 6 respectively). This is why the first operation that is performed is getting the value that the arr variable is pointing to, i.e. this part:
*arr
After this, the addition/subtraction is performed. The value that arr is pointing to doesn't matter since it gets reducted anyway.
This is how you should read this expression:
(*arr) + 5 - (*arr) + 3
and (*arr) - (*arr) is 0, no matter what value it points to.
EDIT: What I've written above is apparently true in your case and your compiler, but look at the #Konrad Rudolph comments to this answer.
And, if you are curious, how the compiler knows if, for example, the '*' should be treated as multiplication or dereference operator: it resolves this problem by looking at the number of arguments - if there's only one, than it's derefence, and if there are two, then it's multiplying.

Related

Difference of Pointer Values

am a novice programmer and I was mingling with pointers to get my base strong for DSA . The following is my code
int main() {
int AnArray[20];
int* plocation6, * plocation0;
plocation6 = &AnArray[6];
plocation0 = &AnArray[0];
cout << (int)plocation6 << endl << (int)plocation0<<endl;
cout << "Difference " << plocation6 - plocation0;
}
And i expected that the value of Difference would be 24 as in Hexadecimal the pointer locations differ by 18 and by 24 in decimal but the answer comes out to be 6 where as if i use convert them using (int) and then do the operation then i get 24 as answer , Why is that? please expalin why 6 comes??
The difference between two pointers isn't in bytes, it's in the number of elements. So you're seeing the number of bytes (24) divided by sizeof(int) (4).
To build on top of the previous answers:
It is true, since an int takes 4 bytes, that the two pointers are 24 bytes apart.
The reason that you are getting 6 is because the - operator (for pointers) is defined as the difference between the two pointer's addresses divided by the size of the data type the pointers point to.
This is a similair concept to operator overloading, where an operator is defined to do something other than the typical operation.
Note: I dont think this is technically operator overloading, but understanding operator overloading will help to understand this concept.
please expalin why 6 comes??
The element at index 0 and the element at index 6 are 6 indices apart. That's where the 6 comes from when you subtract pointer of one from the other.

add array elements with increment operators [duplicate]

This question already has answers here:
Undefined behavior and sequence points
(5 answers)
Closed 7 years ago.
in the below code i am trying to add two elements of array with the increment operator, but i am getting the output sum to be wrong. kindly help me if i made any mistake in the code
#include <stdio.h>
int main(void) {
int a[2];
int top=-1;
a[++top]=10;
a[++top]=20;
printf("a0 is %d \n",a[0]);
printf("a1 is %d \n",a[top]);
printf("value of sum is %d \n",a[top]+a[--top]);
}
the output of last line should be 30 as i and summing the two values in a array. but the out put i get is as follows
a0 is 10
a1 is 20
value of sum is 20
Your program has unspecified behavior. In the expression a[top]+a[--top], the C and C++ language standards do not specify which of a[top] and a[--top] will be evaluated first, and they don't specify when the -- operator is executed relative to other expressions. Compilers can evaluate this as they see fit. Yours is computing --top first, setting top to 0, and then is calculating a[0]+a[0], yielding 20.
Don't use a variable twice in an expression in which you pre- or post- increment or decrement it.
To understand why this is happening, change your last printf to print out top and the sum in one line, like this:
printf("top is %d and the value of the sum is %d \n",top,a[top]+a[--top]);
This should make it apparent that the pre-increment operation is not happening at the point in execution that you think it is.
Try to calculate and print
int y1 = a[top];
int y1 += a[--top];
top = 1;
int y2 = a[top] + a[--top];
this could help you.
The point is that the execution of a[--top]; in your code is done before the execution of a[top] because they are not specified.
Here, in this line:
printf("value of sum is %d \n",a[top]+a[--top]);
Due to --top, top becomes 0 again (--top is --1).
Then a[0] and a[0] are added, and it does not give expected output.
I think it's due to high precedence order of -- operator.
As has been said already, it's better to calculate separately and then print.
PS: Please tell me if anything of the above is wrong or not fully correct. I like to learn from mistakes.

C++ pointer arithmetic logic [duplicate]

This question already has answers here:
Pointer Arithmetic In C
(2 answers)
Closed 8 years ago.
A project I did last year involved pointer arithmetic. When I did that, I was able to treat pointers like memory addresses and add or subtract from them as I wanted. For example, if int* p == array[0], then you'd know that p + sizeof(int) would find array[1]. That doesn't seem to be the case anymore, as I have a relatively well-known interview question in front of me in which I have to debug the following code:
void
ReverseTheArray( const short *pArrayStart, int nArrayByteLength )
{
short const *pArrayEnd = (pArrayStart + nArrayByteLength);
while(pArrayStart != pArrayEnd)
{
short tmp = *pArrayStart;
*pArrayStart = *pArrayEnd;
*pArrayEnd = tmp;
pArrayStart++;
pArrayEnd--;
}
}
Note the last two lines - I would have bet that these were wrong because simply adding 1 to the pointer wouldn't work, you would need to add sizeof(short). But from testing the code it would seem I'm wrong - "pArrayStart++" adds sizeof(short) to the pointer, not 1.
When did this change? Can anyone give me some insight into what I'm wrong about so that I can not look stupid if I'm asked about this?
Edit: Okay - seems like it's always been that way. My bad.
The type of pointer is merely for this purpose. "Pointer to int" means adding one would skip 4 bytes (if int is 4 bytes on that machine.
Update: (Of course, in addition to explaining what type of data it is pointing to).

Array increment with pointers while leaving pointer address unchanged

I am studying for a midterm and one of the questions is Which of the following statements will increment a value in the array, and leave the pointer address unchanged? Circle 0 or more.
int array[10];
int * ptr = array;
1) *ptr++;
2)(*ptr)++;
3)*++ptr;
4)++*ptr;
I have seen 1 and 2 used before and I believe it's just getting the de-referenced values without changing the pointer. But I was surprised to find 3 and 4 is actually valid and I am confused as to how to understand or even read it? Is it the same thing? I believe the answer is that all 4 of them are valid.
http://en.cppreference.com/w/cpp/language/operator_precedence will be helpful to you. Read through it and put the parenthesis in to the examples based on the precedence of the operators and everything will hopefully make some sense.
The first would become *(ptr++) for instance.
Every C++ expression yields a value (main effect). There can also be side effects (as in the examples above) which occur before (e.g. pre-increment in
examples 3 and 4) or after (e.g. post-increment in examples 1 and 2) the main effect. So in your examples:
1) side effect occurs last:
main effect: dereference ptr to get array[0]
side effect: post increment ptr by 4 bytes (on a 32 bit machine)
2) side effect occurs last:
main effect: dereference ptr to get array[0]
side effect: post increment *ptr (=array[0]) by 1
3) side effect occurs first:
side effect: pre increment ptr by 4 bytes (on a 32 bit machine)
main effect: dereference *ptr to get array[0]
4) side effect occurs first:
side effect: pre increment *ptr (= array[0]) by 1
main effect: dereference *ptr to get array[0]
Notice the main effect is obtained by ignoring the side effect operator (++) and is therefore the same in all cases. The main effect is often combined with assignment as in:
int y = *++ptr; // ptr is incrented to point at array[1] and then y becomes equal to *ptr (= array[1])

Difference of two addresses in C [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Pointer Arithmetic
The given code
int arr[12];
int * cur = arr;
cur++;
cout<<"cur-arr = "<<cur-arr<<endl;
Outputs 1, but I expected sizeof(int). Can someone please explain the nature of this behavior?
It's a defined behavior of C pointer arithmetic. It uses the size of pointed type as a unit. If you change subtraction in the last line to
(char *)cur - (char *)arr
you get 4 in the output.
This is the number of elements (ints here) between arr and cur (which is arr+1 at the time of subtraction). Compiler takes note that cur is a pointer to an integer and arr is an integer array. To get total number of bytes, try this:
(cur - arr) * sizeof(arr[0]);
cur is a pointer to int, initialized to some value (arr - the semantics of array-to-pointer conversion are irrelevant here), incremented (cur++) and compared to its old value. Unsurprisingly, it grew by one through the increment operation.
Pointer arithmetic with a given type works just like regular arithmetic. While the pointer is advanced by sizeof(int) bytes in this example, the difference between pointers is also calculated in units of sizeof(int), so you see plain simple arithmetics.
Addition and substraction for pointers works in accordance to the pointer type.