This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

void pointer behaviour ?

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.

Parents
  • When applied to an array, the & operator does nothing.

    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.

    assert (p == q); // this assertion is true
    


    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.

Reply
  • When applied to an array, the & operator does nothing.

    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.

    assert (p == q); // this assertion is true
    


    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.

Children
No data