Any ideas for this typecasting problem?
Here’s what I am trying to do. This is not the actual code:
LinkedList* angles;
double dblangle;
dblangle = (some function for angle calculation returning double value);
(double*)LinkedListCurrent(angles) = &double;
I hope you get the idea. The last line is causing the problem. Initially angles is void* type so I have to first convert it to double*.
You use the unary
*operator to dereference a pointer. Dereferencing a pointer means extracting the value pointed to, to get a value of the original type.edit 2: (deleted edit 1 as it was not relevant to your actual question, but was based on a miscommunication)
From your clarification, it looks like you are wondering how to set a value pointed to by a pointer that has been cast from a
void *to adouble *. In order to do this, we need to use the unary*on the left hand side of the assignment, in order to indicate that we want to write to the location pointed to by the pointer.So, I’m assuming that your
LinkedListCurrentis returning avoid *pointing to some element in the linked list that you would like to update. In that case, you would need to do the following:This updated the value pointed to by the pointer returned from
LinkedListCurrentto be equal todbangle. I believe that is what you are trying to do.If you are trying to update the pointer returned by
LinkedListCurrent, you can’t do that. The pointer has been copied into a temporary location for returning from the function. If you need to return a pointer that you can update, you would have to return a pointer to a pointer, and update the inner one.My explanation above is based on what I believe you are trying to do, based on the example snippet you posted and some guesses I’ve made about the interface. If you want a better explanation, or if one of my assumptions was bad, you might want to try posting some actual code, any error messages you are getting, and a more detailed explanation of what you are trying to do. Showing the interface to the linked list data type would help to provide some context for what your question is about.
edit 3: As pointed out in the comments, you probably shouldn’t be casting here anyhow; casts should be used as little as possible. You generally should use templated collection types, so your compiler can actually do typechecking for you. If you need to store heterogenous types in the same structure, they should generally share a superclass and have virtual methods to perform operations on them, and use
dynamic_castif you really need to cast a value to a particular type (asdynamic_castcan check at runtime that the type is correct).