函数返回类型返回结构指针的编译器抛出错误

时间:2014-12-30 11:34:45

标签: c struct

有人可以解释为什么我在下面的代码中收到编译错误。

错误说:

  

“在第7行”之前预期的'struct'之前的非限定标识“。

我的代码:

struct node{
    int data;
    struct node *left;
    struct node *right;
};

( struct node *) createNode(int num)
{
    struct node *newNode;
    newNode = (struct node *) malloc(sizeof(struct node));
    newNode->data = num;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

4 个答案:

答案 0 :(得分:5)

更改

( struct node *) createNode(int num)

struct node * createNode(int num)

请记住,您正在指定返回类型。你不是typecast

那就是说,

  1. malloc() Cmalloc()家人的回复价值see why not to cast
  2. 在使用返回的指针之前,请务必检查{{1}}的返回值是否成功。

答案 1 :(得分:2)

功能:( struct node *) createNode(int num)语法无效。指向struct node*的指针是函数的返回类型。您似乎可能认为必须将其强制转换为结构类型。这不是必要的。此外,无需在C中投射malloc。将其更改为此。

struct node* createNode(int num)
{
   /* ... */
}

没必要,但是,为了节省每次输入struct,更好的是,您可以使用typedef定义新类型。

typedef struct node Node;

struct node{
    int data;
    Node *left;
    Node *right;
};

答案 2 :(得分:2)

在返回结构时,您不需要为此提供括号。所以,你只需给出

  struct node * createNode(int num){
  ...
  }

放置不正确的括号。

答案 3 :(得分:0)

您不必在函数定义的返回类型中使用括号。我认为你对函数定义感到困惑,这里有几个链接: -

http://www.tutorialspoint.com/cprogramming/c_functions.htm

对于函数返回指针

http://www.tutorialspoint.com/cprogramming/c_return_pointer_from_functions.htm

类型转换只能用于常量,变量,函数调用(如果返回某些内容)。

显式类型转换规则: -

http://www.tutorialspoint.com/cprogramming/c_type_casting.htm