Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a void* within a struct point to an integer

I have a struct as follows:

typedef struct Node {
    void* data;
    unsigned long id;
    NodePtr next;
    NodePtr prev;
} Node;

It is meant to be a node in a linked list ADT. I have 2 different constructors depending on what the Node needs to hold in data. One constructor uses:

NodePtr TempNode;
TempNode = malloc( sizeof(Node) );
/* Other stuff */
TempNode->data = newList();
return (TempNode);

And this seems to work just fine for letting me access that list by returning (List->current->data) where current is a Node pointer in the List Struct

However, I want to make a version of the constructor where (data) points to an int. I've read that I can do this by doing the following

void* ptr;
int x = 0;
*((int*)ptr) = x;

But with the way my constructor is set up, that would mean I have to do something like this?

*((int*)TempNode->data) = 1; // data starts at 1

And this doesn't work. I'm very new to C so I don't understand much of the terminology. I read that dereferencing (using the -> notation?) cannot be done with void*'s, but it seems to work fine in my list version of the constructor. How can I rewrite my other constructor to cast this void* to an int?

like image 282
Ethan Lie Avatar asked Jan 23 '26 06:01

Ethan Lie


1 Answers

I strongly counsel against doing this, but if you really want to use the void * member to hold an integer, you can do:

Node *constructor_int(int n)
{
    Node *tmp = malloc(sizeof(*tmp));
    /* Other stuff */
    tmp->data = (void *)n;
    return(tmp);
}

This involves the minimum number of casts and avoids most problems with relative sizes of types.

The obvious, logical way to do it is to allocate an integer for the data member to point at:

Node *constructor_int(int n)
{
    Node *tmp = malloc(sizeof(*tmp));
    /* Other stuff */
    tmp->data = malloc(sizeof(int));
    *(int *)temp->data = n;
    return(tmp);
}

You just have to remember to free the two memory allocations.

The code should also check that the memory allocations succeeded before using the results.

like image 105
Jonathan Leffler Avatar answered Jan 24 '26 23:01

Jonathan Leffler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!