Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

starting a tree

Status
Not open for further replies.

svar

Programmer
Aug 12, 2001
349
GR
A stupid question maybe, but I am having trouble creating a NULL tree:

#include <stdlib.h>
#include <stdio.h>
struct node {char *data; struct node *left; struct node
*right;} ;
typedef struct node tree ;

void create();
int empty();

main(){
tree t ;
create(&t);

if(empty(&t)){
printf("TREE is empty \n");}
}

void create(tree *t ){/*creates an empty tree */
t =NULL;}

int empty( tree *t ){/* returns 1 if empty*/
return (t ==NULL ? 1 : 0);}


This compiles and runs, but does not print that tree is empty
What am I doing wrong here?
Thanks, svar

 
Take a look at the fix below & see if you can tell what you are doing wrong:

Code:
#include <stdlib.h>
#include <stdio.h>

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

typedef struct node tree;

void create(tree **t);
int empty(tree *t);

int main(void) {
  tree *t;

  create(&t);

  if (empty(t))
    printf("TREE is empty\n");
  return 0;
}

void create (tree **t) {
  *t = NULL;
}

int empty(tree *t) {
  return (t == NULL ? 1: 0);
}

If you are modifying the value (address) held by a pointer, you need to pass the address of the pointer (pass by reference) to the function. Also a few other quibbles that can be seen by the modifications made.

Good Luck!
 
Ok, what I really wanted to do is


int main(void) {
tree t, *t1;

create(&t1);
t=*t1;
if (empty(&t))
printf("TREE is empty\n");
return 0;
}

but I guess the reason I cannot do it is that
t1 is NULL and you cannot get the contents of a NULL address

svar
 
Even if t1 was not NULL, you couldn't do the assignment t=*t1.
You can't assign the contents of a struct to another struct in this manner. You would need to use memcpy as in:

Code:
  create(&t1);
  if (t1 != NULL)
    memcpy(&t,t1,sizeof(t));

What are you really trying to do? Are you trying to initialize t to be 'empty'?
 
OK, thanks, I was just looking at different ways to
delay the use of the structure pointer. Yes, I know, no real need to
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top