Why is malloc() return type causing and error?
I am writing a program to display the nodes of a graph in a depth-first traversal.
however I get these error messages
Error 1 error C2440: '=' : cannot convert from 'void *' to 'mynode *'
2 IntelliSense: a value of type "void *" cannot be assigned to an entity of type "mynode *"
I am using visual studio 2013, the errors come from this line
1 2
|
temp = malloc(sizeof(mynode));
|
and the full implementation is this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
|
#include <stdio.h>
#include <iostream>
using namespace std;
typedef struct node {
int value;
struct node *right;
struct node *left;
} mynode;
mynode *root;
void add_node(int value);
void levelOrderTraversal(mynode *root);
int main(int argc, char* argv[]) {
root = NULL;
add_node(5);
add_node(1);
add_node(-20);
add_node(100);
add_node(23);
add_node(67);
add_node(13);
printf("\n\n\nLEVEL ORDER TRAVERSAL\n\n");
levelOrderTraversal(root);
system("pause");
return 0;
}
// Function to add a new node...
void add_node(int value) {
mynode *prev, *cur, *temp;
temp = malloc(sizeof(mynode));
temp->value = value;
temp->right = NULL;
temp->left = NULL;
if (root == NULL) {
printf("\nCreating the root..\n");
root = temp;
return;
}
prev = NULL;
cur = root;
while (cur != NULL) {
prev = cur;
//cur = (value < cur->value) ? cur->left:cur->right;
if (value < cur->value) {
cur = cur->left;
}
else {
cur = cur->right;
}
}
if (value < prev->value) {
prev->left = temp;
}
else {
prev->right = temp;
}
}
// Level order traversal..
void levelOrderTraversal(mynode *root) {
mynode *queue[100] = { (mynode *)0 }; // Important to initialize!
int size = 0;
int queue_pointer = 0;
while (root) {
printf("[%d] ", root->value);
if (root->left) {
queue[size++] = root->left;
}
if (root->right) {
queue[size++] = root->right;
}
root = queue[queue_pointer++];
}
}
|
If you write in C++, put
|
temp = static_cast<mynode *> ( malloc(sizeof(mynode)) );
|
or use
new
and
delete
instead of malloc() / free().
If you write in C, put
|
temp = (mynode *) malloc(sizeof(mynode)) ;
|
and remember to include the header
<stdlib.h>
Last edited on
First off, are you writing C or C++?
Line 1: This is a C header, not a C++ header.
Line 28,45,79: If you're writing C++, you should be using cout, not printf.
Line 39: Why are you using malloc (assuming you're writing C++). malloc is a C library function. For C++, you should be doing:
If you're writing C, then you need to cast malloc's return value.
|
temp = (mynode *) malloc (sizeof(mynode));
|
Last edited on
Topic archived. No new replies allowed.