用于char*的C中的指针问题

ibr*_*maz 0 c printing char

我使用指针来保存名称和研究实验室属性.但是当我打印现有的顶点时,当我打印顶点时,我无法正确看到所谓的属性.例如,虽然名称的实际值是"lancelot",但我认为它是错误的,例如"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");
    }
Run Code Online (Sandbox Code Playgroud)

Tyl*_*nry 5

当你这样做:

   newV->name=name;
   newV->researchLab=researchLab;
Run Code Online (Sandbox Code Playgroud)

您正在将指针复制到字符串nameresearchLab.你不是自己复制字符串.换句话说,在此之后,newV->namename指向存储名称的内存中完全相同的位置; 您尚未创建数据的副本.

然后,您继续覆盖函数中的name数组createNewPerson,在此函数的末尾,所有vertex结构将使其name属性指向相同的内存位置,该位置仅存储输入的姓氏.

更糟糕的是,当createNewPerson返回时,它的本地name数组超出了范围,并被重新用于其他事情.由于你的顶点结构仍然指向它们的name属性,这就是你如何得到垃圾.

你需要复制字符串.一个简单的方法是:

newV->name = strdup(name);
Run Code Online (Sandbox Code Playgroud)

您需要#include <string.h>获得strdup库函数.

然后,您还需要确保freename处理vertex结构时调用属性.