It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center
                            
                        
                    
                
                                6年前关闭。
            
                    
我有一个问题是为什么要这样做,我只看到了实现

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);

最佳答案

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

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


我认为应该执行以下操作:for循环将i从0向前推进,直到找到nlist元素的nid字段具有空值的元素为止。然后,将该索引处的nidadd字段分别设置为n_idtemp

我应该补充一点,这是非常危险的代码。如果i前进到nlist的末尾而没有找到合适的插槽,则程序很可能崩溃或行为异常。它当然不会正确运行。

09-05 11:46