deref void ptr

This might belong in the beginner forum but here goes:

given:
pointer to struct containing void pointer to data
pointer to struct containing integer value

what is the proper way to index the void pointer with the integer


I can't even come up with something the compiler will accept.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct s
{
  void * data
}
struct t
{
  int foo;
}

main (*argc,*argv[]) {



u_char * ptr =  & ((u_char*) p_s->data)[p_t.foo]; //PTR:unknown size
u_char * ptr =  (*(u_char*) p_s->data)[p_t.foo]; // subscript req. array
u_char * ptr =  & p_s->data[p_t.foo];             // PTR:unknown size
}



arggh..what am i missing

edit: code tags
Last edited on
What is struct s supposed to be? What is p_s and p_t? they aren't even declared. What is a u_char? Where is it defined? You aren't really supposed to dereference a void*. You have to cast it into something meaningful first. Since c++ offers unions, templates and polymorphism, I rarely find a need for the use of the void* concept. At the very least you need an instance of the struct. Perhaps you meant to do this first.

1
2
s* p_s = new s();
t* p_t = new t();


Then you need to allocate memory for whatever data is supposed to be. (don't forget the semicolon after data). I have no idea what you are trying to do.
Last edited on
Since c++ offers unions, templates and polymorphism, I rarely find a need for the use of the void* concept. At the very least you need an instance of the struct.


Very true. But when I neglect my C for too long I tend to forget the precedence rules - especially [] and *. And when the time comes to maintain some legacy code I'm pulling my hair out at 2AM.

Let us assume that, in the above code,

1
2
	unsigned char * temp_ptr_to_char  = (unsigned char *)ptr_to_struct_s->data;
        unsigned char * ptr_to_char            = &temp_ptr_to_char[ptr_to_struct_t.foo];


compiles and runs. How to one line this?
Last edited on
 
unsigned char* temp_ptr = reinterpret_cast<unsigned char*>( p_struct->data ) + p_struct.foo;

Topic archived. No new replies allowed.