Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when a casted pointer has an increment operator?

For example:

int x[100];
void *p;

x[0] = 0x12345678;
x[1] = 0xfacecafe;
x[3] = 0xdeadbeef;

p = x;
((int *) p) ++ ;

printf("The value = 0x%08x", *(int*)p);

Compiling the above generates an lvalue required error on the line with the ++ operator.

like image 817
hopia Avatar asked Mar 19 '11 21:03

hopia


People also ask

What happens when you increment an int pointer?

When a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is a pointer. For Example: If an integer pointer that stores address 1000 is incremented, then it will increment by 2(size of an int) and the new address it will points to 1002.

Why do we increment pointers?

Incrementing the Value of Pointer in an ArrayBecause a pointer points to another value (e.g., an address in memory), it is also useful for array processing. While we can indicate the bucket of an array by using its index, we can also use pointers. For example, the following array shows how the incrementing works.

Can we increment function pointer?

The only things you can do with a function pointer are read its value, assign its value, or call the function that it points toward. You cannot increment or decrement the address stored in a function pointer or perform any other arithmetic operations.

What does increment mean in C++?

In programming (Java, C, C++, JavaScript etc.), the increment operator ++ increases the value of a variable by 1. Similarly, the decrement operator -- decreases the value of a variable by 1. a = 5 ++a; // a becomes 6 a++; // a becomes 7 --a; // a becomes 6 a--; // a becomes 5.


1 Answers

The cast creates a temporary pointer of type int *. You can't increment a temporary as it doesn't denote a place to store the result.

In C and C++ standardese, (int *)p is an rvalue, which roughly means an expression that can only occur on the right-hand side of an assignment.

p on the other hand is an lvalue, which means it can validly appear on the left-hand side of an assignment. Only lvalues can be incremented.

like image 128
Fred Foo Avatar answered Sep 20 '22 21:09

Fred Foo