We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
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.
So the above statement gets the address of an address.
That interpretation would be consistent with the way you'd expect operator & to work, but that behavior doesn't actually match the C spec.
Array names are not always the same as pointers to the first element. Most of the time, yes, but not always.
When applied to an array, the & operator does nothing.
char c[100];
char* p = c; char* q = &c;
assert (p == q); // this assertion is true
(This makes some sense if you ask yourself what &c means. It's the address of the array c, which is the same as the address of its first element. Also, since c is really a constant determined no later than load time, it doesn't really have an address to take. It's not explicitly stored anywhere.)
Similarly, sizeof behaves a little oddly around arrays.
assert (sizeof(c) == 100 * sizeof(char)); assert (sizeof(c) != sizeof(char*));
But, this latter point is only true when sizeof can "see" the array definition. If c were a parameter to a function, then sizeof(c) would indeed be the size of a pointer, no matter what the array declaration was.
"Similarly, sizeof behaves a little oddly around arrays. "
Why, is it bcoz its feels shy of the C compiler or it tends to run away out of "shyness",
Incorrect. It does exactly what it always does: it takes the address of its operand. The difference is that the type of the result is different. &array give you a result of type "pointer to array", not "pointer to element". I.e.
is a warranted assumption only in this particular case, because the base type of the array was 'char', for which special rules apply (because 'char' also serves as the "byte" of C). Strictly speaking,
type array[100]; type *ptr = &array;
is illegal for all types other than character types, because the type of the initializer is different from the type of the object being defined. Lint will not let you get away with this.