when you say:
int *p = ...
p++; /* means p = p + sizeof(int) */
what about void pointers?
void *p = ...
p++; /* compiler error */
as the size of void is unknown.
also,
(int*)pvoid++; // will not compile because the increment operator has higher Precedence than casting
i.e: the casting is for the increment result. so, you are still incrementing a void pointer.
to increment a void pointer you can use
pv = (void*)(((int*) pv)+1);
to increment the void pointer as integer pointer. but, the increment will be with the sizeof(int)
example:
int x[2] = {5,6};
int *p = x;
void *pv = (void*)p ;
pv = (void*)(((int*) pv)+1);
printf("%d\n",*(int*)pv);
or simply you can define a pointer to integer and increment it.
example:
int *p = (int*) pVoid;
p++;
int *p = ...
p++; /* means p = p + sizeof(int) */
what about void pointers?
void *p = ...
p++; /* compiler error */
as the size of void is unknown.
also,
(int*)pvoid++; // will not compile because the increment operator has higher Precedence than casting
i.e: the casting is for the increment result. so, you are still incrementing a void pointer.
to increment a void pointer you can use
pv = (void*)(((int*) pv)+1);
to increment the void pointer as integer pointer. but, the increment will be with the sizeof(int)
example:
int x[2] = {5,6};
int *p = x;
void *pv = (void*)p ;
pv = (void*)(((int*) pv)+1);
printf("%d\n",*(int*)pv);
or simply you can define a pointer to integer and increment it.
example:
int *p = (int*) pVoid;
p++;
3 comments:
what about incrementing a pointer to void after casting it?
e.g.
(*int) pVoid ++;
it will not compile as well. in your example:
(int*)pvoid++; // will not compile because the increment operator has higher Precedence than casting
i.e: the casting is for the increment result. so, you are still incrementing a void pointer.
i have tried it with some other variations. but, it didn't compile as well.
you can use
pv = (void*)(((int*) pv)+1);
to increment the void pointer as integer pointer. but, the increment will be with the sizeof(int)
example:
int x[2] = {5,6};
int *p = x;
void *pv = (void*)p ;
pv = (void*)(((int*) pv)+1);
printf("%d\n",*(int*)pv);
Post a Comment