【发布时间】:2014-02-22 17:05:33
【问题描述】:
我正在尝试编写一个简单的代码来用 C 语言构造一棵树。下面是我的代码 sn-p。
#include<stdio.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
int main()
{
struct node *root = newNode(5);
//struct node *root = NULL; working piece
//newNode(&root,5); working piece
if(root == NULL)
{
printf("No root\n");
return 0;
}
//root->left = newNode(4);
//root->right = newNode(3);
//root->left->left = newNode(2);
//root->right->right = newNode(1);
return 0;
}
struct node* newNode(int data)
{
struct node *temp;
temp = (struct node*) malloc(sizeof(struct node));
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return(temp);
}
当我尝试返回结构节点地址时,编译器给了我错误
"rightNode.c", line 29: identifier redeclared: newNode
current : function(int) returning pointer to struct node {int data, pointer to struct node {..} left, pointer to struct node {..} right}
previous: function() returning int : "rightNode.c", line 12
但是当我评论这个 struct node* newNode(int data) 并尝试定义一个返回 int 的函数时,将结构的地址传递给下面的函数,它没有显示任何错误。
int newNode(struct node **root,int data)
{
printf("Inside New Node\n");
return 0;
}
据我所知,在 C 中将结构体的地址返回给调用函数是合法的。
这与编译器有关。
我在unix环境下使用cc编译器
type cc
cc is a tracked alias for /apps/pcfn/pkgs/studio10/SUNWspro/bin/cc
下面是我用来编译cc rightNode.c的命令
任何帮助将不胜感激......
【问题讨论】:
-
@self-谢谢它没有显示任何错误。但我的疑问是,有必要声明函数的原型吗?如果是这样,为什么在返回 int 时它没有显示任何错误
-
原型,还包括
stdlib.hformalloc -
@arunb2w 编译器会猜测如果函数无法“找到”它,它会返回一个 int。
-
@self - 如果我将 main 函数的返回类型更改为 void,编译器会在不指定原型的情况下猜测被调用函数的返回类型为 void。
-
@arunb2w:C标准明确规定
main的返回类型必须是int。如果类型不是int,则您的程序具有未定义的行为,这意味着它可以工作,但不能保证它会工作。例如,我使用的编译器说main返回void是错误的。