Sunday, August 2, 2009

Help in c language.data structure ?

hi...we need to create a linked list of structures(nodes) using pointers ..the problem when i allocate a place for every new node it gives an error :





#include%26lt;stdio.h%26gt;





struct node{


char name[20];


struct node *next;


};





int main(void){





struct node *p;


//we want to create 3 nodes





for(int i=0;i%26lt;3;i++)


{





p = new node; //AND HERE IT GIVES THE ERROR ('new' undeclared identifier)





so whats the problem ?any help is appreciated

Help in c language.data structure ?
Change the struct as follows:


#define NAME_SIZE 20





struct node{


char name[NAME_SIZE];


struct node *next;


};





int main(void){





struct node *top = NULL;


struct node *newnode;


//we want to create 3 nodes


char buf[256];





for(int i=0;i%26lt;3;i++)


{


newnode = makeNode();


sprintf(buf, "Node # %d", i); /* make a node name */


setName(newnode, buf);





if ( top != NULL) newnode-%26gt;next = top;


top = newnode;





}


}


/* create a function make a node */


struct node * makeNode()


{


p = (node*)malloc(sizeof(node));


/* remember to initialize the node name */


p-%26gt;name[0] = '\0';


p-%26gt;next = NULL;


return p;


}


/* create a function to set the name


* this makes sure that you dont put in a string


* that is too long and overwrite memory.


*/


void setName(struct node * p, char * name)


{


strncpy(p-%26gt;name, name, NAME_SIZE);


/* null terminate the string */


p-%26gt;name[NAME_SIZE-1] = '\0';


}
Reply:"new" is a C++ operator, use malloc for C:





p = (node*)malloc(sizeof(node));
Reply:I think in c you need to do something like:


p = (node*)malloc(sizeof(node));





instead of p = new node;





you may want to check if your struct format is correct as well


No comments:

Post a Comment