簡體   English   中英

鏈接列表突然更改C中的值

[英]Linked list suddenly changes value in C

我正在制作一個簡單的鏈表,問題在於上課時,第一個節點的值發生了變化。 這是我的插入代碼:

int adjob(int job,int time, int size,JOBS **list)
{
    JOBS *temp,*new;
    temp=*list;
    if(temp==NULL)
        *list=create(job,time,size);

    else
    {
        new=(JOBS*)malloc(sizeof(JOBS));
        new->job=job;
        new->size=size;
        new->duration=time;
        new->next=NULL;
        while(temp->next!=NULL)
            temp=temp->next;
        temp->next=new; 
    }
        return 0;
}

這是主要的:

MEM mmem[10];
int main()
{
    int i=1,jtime,jsize,status;
    char option;
    JOBS *joblist;
    joblist=NULL;
    status=initmem(mmem);
    for(;;)
    {
        clrscr();
        printer(mmem,&joblist);
        scanf("%s",&option);
        switch(option)
        {
            case 'I':       if(i<16)
                            {
                                printf("Input size of job %i: ",i);
                                scanf("%i",&jsize);
                                printf("Input duration: ");
                                scanf("%i",&jtime);
                                status=adjob(i,jtime,jsize,&joblist);
                            }
                                i++;
                                break;
            case 'S':       break;
            case 'R':       break;
            case 'E':       exit(0);
        }
    }
    free(joblist);
    joblist=NULL;
    return 0;
}

這些是我的結構:

struct node
{
    int job;
    int size;
    int duration;
    struct node *next;
};

struct mainmem
{
    int memblock;
    int size;
    int jobnum;
    int jobsize;
    int timer;
};
typedef struct mainmem MEM;
typedef struct node JOBS;

然后這是我的打印機:

int printer(MEM *mymem,JOBS **list)
{
    JOBS *temp;
    int i=0,pr=3;
    temp=*list;

    /*MEM LIST*/
    printf("\t\tMEMORY LIST\t\t\t\tJOB LIST\nMem Block    Size    Job    Job Size    Timer\n");
    while(i!=10)
    {
        printf("   %i\t     %i\n",i+1,mymem[i].size);
        i++;
    }
    /*JOB LIST*/
    gotoxy(50,2);
    printf("Job no.\tTime\tJob Size");
    if(temp==NULL)
    {
        gotoxy(50,pr);
        printf("No jobs on queue.");
    }
    else
    {
        while(temp!=NULL)
        {   
            gotoxy(50,pr);
            printf("%i\t%i\t%i",temp->job,temp->duration,temp->size);
            pr++;
            temp=temp->next;
        }
    }
    gotoxy(1,20);
    printf("[I]-INPUT   [S]-START   [R]-RESULT  [E]-EXIT\n");
    return 0;
}

第一個節點插入沒有問題。 當我插入第二個節點時,第一個節點會更改。 當我嘗試插入超過2時,程序將按原樣運行。 我嘗試調試它,當在JOBS LL中插入第二個輸入時,該值會更改,但是我無法從代碼中弄清楚。 可能出了什么問題?

您遇到的問題可能是因為您的代碼中存在未定義的行為 :variable option是一個char ,但是您將其讀為一個字符串,該字符串將寫入兩個字符(讀取的字符字符串終止符)。 沒有辦法知道將覆蓋哪些內容,但是可能會覆蓋存儲其他局部變量的堆棧部分。

您應該將輸入處理更改為僅讀取單個字符:

scanf(" %c", &option);

請注意前導空格,它將告訴scanf讀取並丟棄字符前面的任何空格(包括換行符)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM