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.
Hi,
independend from the void or int pointer type, the statement "ptr = (int *)&a;" is wrong.
If a array is defined, the name of the array is the address. So the above statement gets the address of an address.
Correct is either: ptr = (int *)a; or ptr = (int *)&a[0];
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",
View all questions in Keil forum