-2

我得到了这个问题的原因,我只看到了实现

for(i=0;nlist[i].nid!=0;i++)
        {}
        nlist[i].nid=n_id;
        nlist[i].add=temp;

nlist 是类型结构的数组

结构

struct node
{
    int id; 
    struct node *l[MAX_CONN+1];
    int cost[MAX_CONN+1];  
    struct node **next;
    int *mincost;

};
typedef struct node nodes; 
struct record 

{
    int nid;
    struct node *add;
};
typedef struct record records;
records nlist[MAX_NODES+1]={0};

全功能

    FILE *f;
    int d;
    int i=0,j=0,n_id,n_cost;
    nodes *temp=0,*temp1=0;

    if((f=fopen("graph.txt","r"))== NULL)
    {
        printf("Error opening file.\n");
        exit(1);
    }
    memset(nlist, 0, sizeof(struct record) * MAX_NODES);
    count=0;
    do /*first get the id and address of all nodes*/
    {
        fscanf(f,"%d",&n_id);
        for(i=0;nlist[i].nid!=0;i++)
        {
            if(n_id==nlist[i].nid)
            {
                printf("Id already exists.");
                return;
            }
        }
        temp=(nodes *)malloc(sizeof(nodes));
        if (temp == 0)
        {
           printf("ERROR: Out of memory\n");
           return;
        }
        memset(temp, 0, sizeof(struct node));
        temp->id=n_id;
        temp->l[MAX_CONN+1]=0;
        temp->cost[MAX_CONN+1]=0;
        for(i=0;nlist[i].nid!=0;i++)
        {}
        nlist[i].nid=n_id;
        nlist[i].add=temp;
        count++;
        while((d=fgetc(f)!=';'))
        {}
    }while((d=fgetc(f))!=EOF);

    rewind(f);

    for(i=0;i<count;i++) /*now get the information of all nodes connections.*/
    {
        fscanf(f,"%*d");

        temp=nlist[i].add;
        while((d=fgetc(f)!=';'))
        {
            fscanf(f,"%d-%d",&n_id,&n_cost);
            for(j=0;nlist[j].nid!=0;j++)
            {
                if(nlist[j].nid==n_id)
                {
                    temp1=nlist[j].add;
                    break;
                }
            }
            for(j=0;temp->cost[j]!=0;j++)
            {}
            temp->cost[j]=n_cost;
            temp->l[j]=temp1;
        }
    }
    fclose(f);
4

1 回答 1

2

缩进具有误导性。它应该像这样缩进:

for(i=0;nlist[i].nid!=0;i++) {
    /* empty loop */
}
nlist[i].nid=n_id;
nlist[i].add=temp;

我认为它应该做的事情如下:for循环i从 0 开始,直到它找到一个元素的字段nlist为空值nid。然后,它将该索引处的nid和字段分别设置为和。addn_idtemp

我应该补充一点,这是非常危险的代码。如果在没有找到合适的插槽i的情况下前进到末尾nlist,程序很可能会崩溃或以其他方式出现异常。它肯定不会正确运行。

于 2013-03-10T04:26:54.770 回答