Thread: question about pointers, cast

  1. #1
    Registered User
    Join Date
    Apr 2004

    question about pointers, cast

    Hello, I've experience programming in C, but am new (somewhat) to C++. Please take a look at this snippet below. I haven't been active in C for a while, but would think it would work without the cast of (<type> *).
    Am I remembering wrong, or, since I'm using a C++ compiler (G++, using Dev-C++), is that affecting the results?

    #define BYTE unsigned char
    #define ULONG unsigned long int

    void POKE (ULONG *, BYTE);

    int main(int argc, char *argv[])

    int a=5;
    ULONG *p_a;
    char key;

    p_a=(ULONG *)&a;
    POKE(p_a, 0xff);

    As it is, this compiles fine and works as I would expect. And for example, if I code:
    p_a=(ULONG *)0x5000

    this makes sense to me because I don't actually have an address of a variable for the variable reference operator &, so I should be stating p_a points to a ULONG , and not the value of 0x5000, but the cast by (ULONG *) is the address supplied.

    But without the (<type> *) cast, I get an error compiling. Since I have a variable 'a' above (type int), shouldn't:

    suffice? What am I missing here? Am I losing my marbles, or just rusty with this stuff?

    Thanks in advance.

  2. #2
    Registered User
    Join Date
    Jan 2003
    Try a better cast:
    p_a = reinterpret_cast <ULONG *> (&a);
    Last edited by Speedy5; 04-20-2004 at 03:50 PM.

  3. #3
    Confused Magos's Avatar
    Join Date
    Sep 2001
    int and unsigned long int are different types, so they need to be typecasted. p_a=(ULONG)&a wouldn't work well since you're trying to cast a pointer into a normal variable. At any rate, take Speedy's adcive and use templated C++ casts instead of old C ones.

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A question about pointers in C
    By Kilua in forum C Programming
    Replies: 3
    Last Post: 06-05-2009, 02:33 AM
  2. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  3. simple pointers question
    By euphie in forum C Programming
    Replies: 4
    Last Post: 05-25-2006, 01:51 AM
  4. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  5. Quick Question Regarding Pointers
    By charash in forum C++ Programming
    Replies: 4
    Last Post: 05-04-2002, 11:04 AM