簡體   English   中英

為什么我得到這個錯誤的輸出?

[英]Why I get this wrong output?

我創建了這個簡單的雙向鏈表。 問題是,當我打印其所有元素時,即使變量“a”每次都發生變化,它們也具有相同的 char 值。

typedef struct node{
char *name;
struct node *n;
struct node *p;
} N;

N *h=NULL;//head

void insert(char *value){
N *temp=malloc(sizeof(N));
if(h==NULL){
    h=temp;
    temp->name=strdup(value);
}
else{
    N *curr=h;
    while(curr->n!=NULL)
        curr=curr->n;
    curr->n=temp;
    temp->p=curr;
    temp->name=strdup(value);
}
}

void print(){
N *temp=h;
printf("%s\n", temp->name);
while(temp->n!=NULL){
    printf("%s\n", temp->name);
    temp=temp->n;
}
}


int main(){

char a[...];
fgets(a,...)

//there is a while section: every time i enter in it, there is:
char *input=a;
insert(input);
print();
}

所以我期望的是:獅子熊山羊......相反,我得到:獅子,然后是熊熊,然后是山羊山羊山羊

等等...

您為每個列表元素指向相同的內存。 這段代碼

temp->name=value;

由於結構的定義,僅將指針復制到temp->name

typedef struct node{
char *name;
struct node *n;
struct node *p;
} N;

name只是一個指針。 您需要復制value指向的字符串,而不僅僅是將name指向value (輸入驗證和錯誤檢查留給讀者作為練習......):

char *duplicateString( const char *inputString )
{
    char newString = malloc( strlen( inputString ) + 1 );
    strcpy( newString, inputString );
    return( newString );
}

所以

temp->name = duplicateString( value );

請記住在調用free( temp )釋放節點之前調用free( temp->name )

或者如果您在 POSIX 系統上使用strdup()

temp->name = strdup( value );

有幾個問題。 首先,您在 print() 中有一個錯誤,該錯誤阻止顯示最后一個值。 檢查 temp 而不是 temp->n:

void print()
{
    N *temp=h;

    while(temp !=NULL){
       printf("%s\n", temp->name);
       temp=temp->n;
   }
}

您額外的 printf() 調用(在 while 循環之前)是第一個值被打印兩次的原因。

此外,您必須在添加新節點時分配 p 和 n。 如果您不分配它們,則不能假設它們將為 NULL。

void insert(char *value)
{
    N *temp=malloc(sizeof(N));
    if(h==NULL){
        h=temp;
        temp->p = NULL;
        temp->n = NULL;
        temp->name=strdup(value);
    }
    else{
        N *curr=h;
        while(curr->n!=NULL)
        curr=curr->n;
        curr->n=temp;
        temp->p=curr;
        temp->n = NULL;
        temp->name=strdup(value);
   }
}

另外,您需要將列表雙向鏈接嗎? 你從不使用 p 指針。

暫無
暫無

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

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