i use pointer for holding name and research lab property. But when i print the existing Vertex ,when i print the vertex, i cant see so -called attributes properly.
For example though real value of name is “lancelot” , i see it as wrong such as “asdasdasdasd”
struct vertex {
int value;
char*name;
char* researchLab;
struct vertex *next;
struct edge *list;
};
void GRAPHinsertV(Graph G, int value,char*name,char*researchLab) {
//create new Vertex.
Vertex newV = malloc(sizeof newV);
// set value of new variable to which belongs the person.
newV->value = value;
newV->name=name;
newV->researchLab=researchLab;
newV->next = G->head;
newV->list = NULL;
G->head = newV;
G->V++;
}
/***
The method creates new person.
**/
void createNewPerson(Graph G) {
int id;
char name[30];
char researchLab[30];
// get requeired variables.
printf("Enter id of the person to be added.\n");
scanf("%d",&id);
printf("Enter name of the person to be added.\n");
scanf("%s",name);
printf("Enter researc lab of the person to be added\n");
scanf("%s",researchLab);
// insert the people to the social network.
GRAPHinsertV(G,id,name,researchLab);
}
void ListAllPeople(Graph G)
{
Vertex tmp;
Edge list;
for(tmp = G->head;tmp!=NULL;tmp=tmp->next)
{
fprintf(stdout,"V:%d\t%s\t%s\n",tmp->value,tmp->name,tmp->researchLab);
}
system("pause");
}
When you do this:
You are copying the pointer to the strings
nameandresearchLab. You are not copying the strings themselves. In other words, after this,newV->nameandnamepoint to exactly the same location in memory where the name is stored; you have not created a duplicate copy of the data.Since you then proceed to overwrite the
namearray in thecreateNewPersonfunction, at the end of this function, all of yourvertexstructs will have theirnameattribute pointing to the same memory location, which is only storing the last name entered.Worse, when
createNewPersonreturns, its localnamearray goes out of scope, and is re-used for other things. Since your vertex structs are still pointing here for theirnameattributes, this is how you get garbage.You need to duplicate the string. A simple way to do it is:
You will need to
#include <string.h>to get thestrduplibrary function.And then you also need to make sure that you call
freeon thenameattribute whenever you are disposing of avertexstructure.