Welcome, Guest. Please login or register.

Author Topic: assignment problem with general pointers (VOID type )  (Read 1283 times)

Description:

0 Members and 1 Guest are viewing this topic.

Offline Trev

  • Zero
  • Hero Member
  • *****
  • Join Date: May 2003
  • Posts: 1550
  • Country: 00
    • Show all replies
Re: assignment problem with general pointers (VOID type )
« on: December 30, 2004, 03:46:31 AM »
So you're trying to assign a `APTR' (typedef void *APTR) to a `struct Pixel *'? Well, in C, this should work:

APTR ptr;
struct Pixel *pixel;

func(&ptr);
pixel = (struct Pixel *)ptr;

In C++, your compiler might let you do something like this:

APTR ptr;
BYTE red;

func(&ptr);
red = static_cast(ptr)->Red;
static_cast(ptr)->Red = 0xff;

Trev
 

Offline Trev

  • Zero
  • Hero Member
  • *****
  • Join Date: May 2003
  • Posts: 1550
  • Country: 00
    • Show all replies
Re: assignment problem with general pointers (VOID type )
« Reply #1 on: December 30, 2004, 08:15:34 PM »
You don't need a union for this. In fact, using a union for a type conversion would be an incorrect use of a union. It's only safe to read from a member of a union if that member was the last member written to:
Code: [Select]

struct my_struct {
  union {
    int int_val;
    void* ptr;
  };
};

void some_func()
{
  struct my_struct ms;
  void* ptr;

  ms.int_val = 1;
  ptr = ms.ptr; /* UNSAFE--newer compilers should issue a warning */
}

Anyhow, you should use unions when you want to conserve memory and you know exactly how your compiler and linker organizes structures and data in general in memory.

The code samples from my previous message were just samples of casting in C/C++. func() was just a hypothetical function that took a pointer to a pointer as a parameter. This might be clearer:
Code: [Select]

struct sample_struct {
  int value1;
  int value2;
};

APTR func(void); /* hypothetical function returns a pointer to struct sample_struct as a APTR */

int main(void)
{
  APTR ptr;
  struct sample_struct* ss;

  ptr = func();
  ss = (struct sample_struct*)ptr;
  ss->value1 = 1;

  /* OR */

  ss = (struct sample_struct*)func();
  ss->value1 = 1;
}

Now might be a good time to go over the rules for casting in the C standard. :-) If you're not using C++, then you can ignore my static_cast sample.

Also note that these are just casting examples. Be sure to keep on eye on those pointers, especially if they point to memory that needs to be deallocated.

Trev