Nathan.C.Jones
Nathan.C.Jones

Reputation: 13

Retrieving memory address with multiple nested struct pointers

I have a (hopefully) very simple issue that has been giving me problems for a while now. Given these structs

typedef struct
{
    void * entity;
} link_t;

typedef struct
{
    link_t * current;
} list_t;

and a function prototype

void *list_get_entity(list_t *list);

I need the function list_get_entity to return the address of the data that "entity" is pointing to. The best I've been able to do so far is

void *list_get_entity(list_t *list)
{
     return list->current->entity;
}

which at least compiles and runs, but gives me gibberish. If for some reason the full file is needed to figure something out please let me know, although I'm sure there's other bugs in there I have yet to find because of this error.

Edit: fixed the code

Upvotes: 0

Views: 66

Answers (2)

m. c.
m. c.

Reputation: 895

typedef struct
{
   void * entity;
} link_t;

typedef struct
{
   link_t * current;
} list_t;

void * list_get_entity(list_t *list)
{
  return list->current->entity;
}

list->current is a pointer to link_t; list->current->entity is a pointer to entity type. If you add &() around list->current->entity, it becomes pointer to pointer to void.

Upvotes: 1

JaredPar
JaredPar

Reputation: 754665

To get the address of the data entity is pointing to just return it directly

return list->current->entity;

The void* is an address hence returning it directly by value will give the caller the address of the data

Upvotes: 1

Related Questions