Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I modify a pointer to void through a function?

I'm trying to create a linked list where you can update the data in a node, but no matter what I try, C doesn't seem to allow me to update the value of a void pointer (or rather where it points to). Here's the test code I have:

void newData(void * d)
{
    char data[] = "world";

    d = &data;
}

int main()
{
        char testData[] = "hello";
        void * testPointer = &testData;

        printf("TestData is %s\n", (char *)testPointer);

        // Modify the data
        newData(&testPointer);

        printf("TestData is %s\n", (char *)testPointer);
}

Which just outputs::

TestData is hello
TestData is hello

Am I missing something obvious here? I've also tried using a pointer to a pointer, but to no avail.

like image 664
Lewis Avatar asked Mar 21 '26 05:03

Lewis


1 Answers

I think you need

void newData(void ** d) 
{
    char data[] = "world";
    *d = &data;  
}     

However, this has it's own problems, as "world" is stack local, and won't be valid after you return from newData.

like image 72
AShelly Avatar answered Mar 22 '26 21:03

AShelly



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!