So I’m following a tutorial on C and I’m stuck at structs since they use the malloc function and that function doesn’t seem to go well with my compiler (Visual Studio C++ 10.0). So I followed the instructions exactly and I can compile C except that in this particular code, it gives me an error (code taken literally from the tutorial website):
#include <stdio.h>
#include <stdlib.h>
struct node {
int x;
struct node *next;
};
int main()
{
/* This won't change, or we would lose the list in memory */
struct node *root;
/* This will point to each node as it traverses the list */
struct node *conductor;
root = malloc( sizeof(struct node) );
root->next = 0;
root->x = 12;
conductor = root;
if ( conductor != 0 ) {
while ( conductor->next != 0)
{
conductor = conductor->next;
}
}
/* Creates a node at the end of the list */
conductor->next = malloc( sizeof(struct node) );
conductor = conductor->next;
if ( conductor == 0 )
{
printf( "Out of memory" );
return 0;
}
/* initialize the new memory */
conductor->next = 0;
conductor->x = 42;
return 0;
}
The malloc function kept giving trouble: “a value of type void cannot be assigned to an entity of type “node *” so I cast (node *) to every malloc-containing line, i.e.:
root = malloc( sizeof(struct node) );
etc. This seemed to solve the above mentioned error but then when I did that and tried to compile a new error came up:
1>------ Build started: Project: TutorialTest, Configuration: Debug Win32 ------
1> TutorialTest.c
1>c:\users\ahmed\documents\visual studio 2010\projects\tutorialtest\tutorialtest\tutorialtest.c(16): error C2065: 'node' : undeclared identifier
1>c:\users\ahmed\documents\visual studio 2010\projects\tutorialtest\tutorialtest\tutorialtest.c(16): error C2059: syntax error : ')'
1>c:\users\ahmed\documents\visual studio 2010\projects\tutorialtest\tutorialtest\tutorialtest.c(27): error C2065: 'node' : undeclared identifier
1>c:\users\ahmed\documents\visual studio 2010\projects\tutorialtest\tutorialtest\tutorialtest.c(27): error C2059: syntax error : ')'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
So yeah, after (as a complete C newbie) trying to figure this out for half an hour, I couldn’t come up with the solution. How can I solve this error? I’m starting to think it’s a compiler issue, but I don’t want to change compiler if it’s not a necessity.
The problem is that you’re compiling C code with a C++ compiler. C allows that conversion from
void *to an object pointer; C++ doesn’t.You say that you added a cast, but didn’t show us what it looked like. If it looks like this, then the code should compile as both C and C++:
Alternatively, there might be a way to tell the compiler to treat it as C, but I don’t know enough about that compiler to help you there.