Hi, I observed a strange behaviour (for me only) of void pointer. I wrote a code to access an integer through void pointer as below:
void *ptr; int a[2] = {1,2};
ptr = (int *)&a; ptr++; // This is giving error: Unknown Size
Why the above increment statement is giving error as i already cast the pointer to int type ?
Can anybody help me in understanding this ?
Karthik K.
Setting a void pointer to the address of an object does not change the pointer's type; it's still a void pointer.
For example, if you assigned the address of a function to a void pointer and then tried to increment the pointer, what result would you expect?
then whats the correct way?
whats the correct way?
Depends on what you are trying to do. If you are really only going to use this pointer to point to int, then make it a pointer to int. If not, explain what you are trying to do.
- mike
((int *)ptr)++;
Jon
Jon, I was trying to encourage a good style of programming in C, and you ruined it by showing an easy workaround :-) Ah well, let him learn the hard way.
Thanks to all for guiding me... So if i understood correctly, then i can say that whenever i need to access void pointer, i have to cast it to proper type.
Well, I want to improve my C knowledge. Can anyone suggest a way... ?
warning: #1441-D: nonstandard cast on lvalue
Is that ok?
ya ok,
"((int *)ptr)++;
Is that ok?"
Although some compilers accept it, it's really an error because the postfix increment operator requires a modifiable lvalue and a cast does not yield an lvalue.
What does work on all compilers is:
ptr = ((int *)ptr) + 1;
Thats absolutely true ..!!
View all questions in Keil forum