问题
#include <stdlib.h>
#include <stdio.h>
// self - referential structure
struct listNode {
char data; // each listNode contains a character
struct listNode *nextPtr; //pointer to next node
};
typedef struct listNode ListNode; // synonym for struct listNode
typedef ListNode *ListNodePtr; // synonym for struct listnode*
void insert(ListNodePtr *sPtr, char value)
{
ListNodePtr newPtr = malloc(sizeof(ListNode)); // create node
if (newPtr != NULL) // is space availale?
{
newPtr->data = value; // place value in node
newPtr->nextPtr = NULL; // node does not link to another node
ListNodePtr previousPtr = NULL;
ListNodePtr currentPtr = *sPtr;
// loop to find the correct location in the list
while (currentPtr != NULL && value > currentPtr->data)
{
previousPtr = currentPtr; // walk to...
currentPtr = currentPtr->nextPtr; // ... next node
}
if (previousPtr == NULL) // insert new node at beginning of list
{
newPtr->nextPtr = *sPtr;
*sPtr = newPtr;
}
else
{
previousPtr->nextPtr = newPtr;
newPtr->nextPtr = currentPtr;
}
}
else
{
printf("%c not inserted. No memory available. \n", value);
}
}
this is my function, the problem happens in line "ListNodePtr newPtr = malloc(sizeof(ListNode));" It says Cannoy convert void to ListNotePtr Then it says IntelliSense: A value of type "void *" cannoy be used to initialize entity of type "ListNodePtr"
I'm a bit confused because I copied this function straight from my lecture slides, but I cannot seem to make it work. Anybody know what's going on? This function and others are called in main(void). Thank you in advance!
回答1:
It seems to be that you are assigning a void type value to a ListNodePtr variable. If you are compiling with a C++ compiler, you need to perform an explicit cast:
void insert(ListNodePtr *sPtr, char value)
{
ListNodePtr newPtr = (ListNodePtr)malloc(sizeof(ListNode));
// ...
There is a similar issue here : https://stackoverflow.com/a/15106036/5810934.
来源:https://stackoverflow.com/questions/36757535/error-c2440-initializing-cannot-convert-void-to-typ