can i initializing one list with another list?
if yes to where my newlist->next should point (relative to the old list or not!)?
tanq
can i initializing one list with another list?
if yes to where my newlist->next should point (relative to the old list or not!)?
tanq
What do you mean?.. do you want an empty list point to another? in that case you would assign the head of the old list to the head of the new one.
no,i have a list, and i want to copy it to another empty list and make some action which i dont want to effect the origin(old list) list and i dont know how!
Code:typedef struct Person { int id; char* name; struct PersonList* friends; } Person; typedef struct PersonList { Person* person; struct PersonList* next; } PersonList;
do u have any solution?Code:void copy(PersonList* allPersons) { int max=0,numfr=0; PersonList *newlist=0; newlist=(PersonList*) malloc(sizeof(PersonList)); while(allPersons) { newlist->person=(Person*)malloc(sizeof(Person)); newlist->person->name=(char*)malloc(100*sizeof(char)); newlist->person->friends=(PersonList*) malloc(sizeof(PersonList)); newlist->person=allPersons->person; strcpy(newlist->person->name,allPersons->person->name); newlist->person->friends=allPersons->person->friends; newlist->person->id=allPersons->person->id; newlist->next= //i dont know what to do here!!!!!<<<<<<<<<<<<< allPersons=allPersons->next; } }
yes, why does your function not return anything? in that function you can modify the list but you can't change the value of "PersonList* allPersons" which is a pointer. thus the assignment "allPersons=allPersons->next;" modifies nothing.
u say even if i change allPersons its wont affect the origin list?
Now should be ok! ;-)Code:PersonList *copyt(PersonList *allPersons) { int max=0,numfr=0; PersonList *newlist=0; while(allPersons) { newlist=(PersonList*) malloc(sizeof(PersonList)); newlist->person=(Person*)malloc(sizeof(Person)); newlist->person->name=(char*)malloc(100*sizeof(char)); /* you shouldn't allocate memory for the friends cause then you should copy also that list */ //wrong newlist->person->friends=(PersonList*) malloc(sizeof(PersonList)); // here you are just copyng an address not the structure //wrong newlist->person=allPersons->person; strcpy(newlist->person->name,allPersons->person->name); newlist->person->friends=allPersons->person->friends; newlist->person->id=allPersons->person->id; newlist=newlist->next; allPersons=allPersons->next; } return newlist; }
Sorry i forgot that you have to use a tmp variable to store the address of the newlist head, otherwise that function will return the last node (NULL!!)
Last edited by flexo87; 07-04-2009 at 11:08 AM. Reason: MISSAT
tanx man y r a lifesaver