Pointer Arithmetic and Typecasting

This is a discussion on Pointer Arithmetic and Typecasting within the C Programming forums, part of the General Programming Boards category; Hi... Ok, there's no real purpose to this, I'm just bored... Anyway, basically I want to be able to manipulate ...

  1. #1
    Registered User
    Join Date
    May 2008
    Location
    Australia
    Posts
    230

    Pointer Arithmetic and Typecasting

    Hi... Ok, there's no real purpose to this, I'm just bored... Anyway, basically I want to be able to manipulate a void pointer by assigning it the address of an integer, and try and manipulate the value of that integer via dereferencing and typecasting the void pointer and assigning it a value.

    I'm trying to do it like so:

    Code:
    int y = 0;
    void * x = &y;
    (int *)(*x) = 5;
    My take on the above is:

    declare a void pointer and give it the address of the 'y' integer.
    derference the pointer and typecast to a pointer to an integer.

    I get the following compile errors:

    Code:
    error C2100: illegal indirection	
    warning C4047: '=' : 'int *' differs in levels of indirection from 'int'
    Could someone please explain to me what I'm doing wrong, how I can accomplish this, why, and how, etc.

    Trying to get a better understanding of the above.

    Thanks!
    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,593
    What you are doing here is dereferencing a void pointer and then casting the result to int*, and then assigning 5 to the result:
    Code:
    (int *)(*x) = 5;
    What you probably want to do is to cast the void pointer to int*, then dereferencing the result and assigning 5 to the final result:
    Code:
    *(int *)x = 5;
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    May 2008
    Location
    Australia
    Posts
    230
    Quote Originally Posted by laserlight View Post
    What you are doing here is dereferencing a void pointer and then casting the result to int*, and then assigning 5 to the result:
    Code:
    (int *)(*x) = 5;
    What you probably want to do is to cast the void pointer to int*, then dereferencing the result and assigning 5 to the final result:
    Code:
    *(int *)x = 5;
    That worked, thanks a lot, I understand
    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21