简体   繁体   English

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

[英]Compiler throwing error for function return type returning structure pointer

Can someone please explain why am I getting the compilation error the below code. 有人可以解释为什么我在下面的代码中得到编译错误。

Error says: 错误提示:

"expected unqualified-id before 'struct' " on line number 7 ". “第7行的'struct'之前的预期非限定ID”。

My code: 我的代码:

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;
}

change 更改

( struct node *) createNode(int num)

to

struct node * createNode(int num)

Remember, you're specifying the return type . 记住,您要指定返回类型 You're not typecast ing. 您不是在typecast

That said, 那就是

  1. Please see why not to cast the return value of malloc() and family in C . 查看为什么不在 Cmalloc()和family的返回值。
  2. Always check for the return value of malloc() for success before using the returned pointer. 在使用返回的指针之前,请务必检查malloc()的返回值是否成功。

Function: ( struct node *) createNode(int num) is invalid syntax. 函数: ( struct node *) createNode(int num)语法无效。 A pointer to a struct node* is the return type of the function. 指向struct node*指针是struct node*的返回类型。 It seems you may have thought you must cast it to the struct type. 似乎您可能已经认为必须将其强制转换为struct类型。 That is not necessary. 那是没有必要的。 Furthermore, there is no need to cast malloc in C. Change it to this. 此外,无需在C中malloc 。将其更改为此。

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

Not necessary, but, to save on typing struct each time, better yet, you can define a new type with typedef . 不必要,但是为了节省每次键入struct好处,更好的是,您可以使用typedef定义一个新类型。

typedef struct node Node;

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

While returning the structure you don't need to give the parenthesis for that. 返回结构时,您无需为此加上括号。 So simply You give the 所以简单地你给

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

Placing the brackets that is not correct. 放置不正确的括号。

You dont have to use parenthesis in return type of function definition. 您不必在函数定义的返回类型中使用括号。 I think you are confused with the function definition here are few links:- 我认为您对函数定义感到困惑,这里的几个链接:

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

For function returning pointers 对于函数返回指针

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

Type casting can only be use to a constant, variable, function calls (if returning something). 类型转换只能用于常量,变量,函数调用(如果返回某些内容)。

Explicit type conversion rule:- 显式类型转换规则:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM