It's amazing how even the littlest program can cause so much trouble in C.
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int value;
struct node *leftChild;
struct node *rightChild;
} node;
typedef struct tree {
int numNodes;
struct node** nodes;
} tree;
tree *initTree() {
tree* tree = (tree*) malloc(sizeof(tree));
node *node = (node*) malloc(sizeof(node));
tree->nodes[0] = node;
return tree;
}
int main() {
return 0;
}
The compiler says:
main.c: In function 'initTree':
main.c:17: error: expected expression before ')' token
main.c:18: error: expected expression before ')' token
Can you please help?
Don't use
typedef
'ed names as variable names, and there is not need to castmalloc();
in C.Change the body of initTree as follows:
Interestingly, it does compile cleanly if you simply write the allocations as:
It is often considered better style to use "sizeof variable" rather than "sizeof( type )", and in this case the stylistic convention resolves the syntax error. Personally, I think this example is a good case demonstrating why typecasts are generally a bad idea, as the code is much less obfuscated if written:
You're using two variables named
tree
andnode
, but you also have structstypedef
ed astree
andnode
.Change your variable names:
Apart from the original question, this code, even in it's correct forms will not work, simply due to the fact that
tree::nodes
(sorry for the C++ notation) as a pointer to a pointer will not point to anything usefull right after atree
as been malloced. Sotree->nodes[0]
which in the case of ordinary pointers is essentially the same like*(tree->nodes)
, can't be dereferenced. This is a very strange head for a tree anyway, but you should at least allocate a singlenode*
to initialize that pointer to pointer:tree
andnode
is your case are type names and should not be used as variable names later on.