2017-03-23 38 views
1

這是什麼應該做的是:如何實現[複製數組到鏈表]功能?

  • 有4個元素創建一個數組。

  • 打印這4個元素。

  • 將數組元素複製到創建的鏈接列表中。

  • 打印鏈接列表與打印和遍歷功能。

我試過這個,它編譯,但打印數組後崩潰。

#include<stdio.h> 
#include<stdlib.h> 
#include<malloc.h> 
#define ELEMENTS 4 

struct node 
{ 
    int data; 
    struct node *next; 

}; 
struct node*head; 

void insert(int x) 
{ 

    struct node*temp= malloc(sizeof(struct node)); 
    temp->data = x; 
    temp->next = NULL; 
    if(head != NULL) temp->next = head; 
    head=temp; 


} 
void copy(struct node*head ,int array[ELEMENTS],int n)       //copying array elements and create linked list 
{ 
    struct node*temp = malloc(sizeof(struct node)); 
    temp->data=array[0]; 
    temp->next=NULL; 
    head =temp; 
    int i; 
    for(i=1;i<n;i++) 
    { 
     struct node*temp2= malloc(sizeof(struct node)); 
     temp->next= temp2; 
     temp2->data = array[i]; 
     temp2->next = NULL; 
     temp=temp2; 



    } 


} 

void printlist() 
{ 
    struct node*temp = head; 
    printf("List is : "); 


    while(temp->next!=NULL) 
    { 
     printf(" %d ",temp->data); 
     temp=temp->next; 

    } 
    printf("\n"); 


} 

int main() 
{ 
    int *array=(int*)calloc(ELEMENTS , sizeof(int)); 
    int i = 0; 
    for(i=0;i<ELEMENTS;i++) 
     { 
      printf("arrays = [%d] ",i); 
      scanf("%d", &array[i]); 
     } 

     for(i=0;i<ELEMENTS;i++) printf("array [%d] = %d \n", i,array[i]); 


     copy(head ,array[ELEMENTS],ELEMENTS); 

     printlist(); 








     getchar(); 
     return(0); 
} 

如何解決?

+0

運行代碼一個調試器並對其進行調試。 – barny

回答

1

你不需要通過headcopy功能,因爲它是全球性的,當你做,你創建一個名爲head其中,即會破壞當地的指針作爲函數結束。

所以copy應該是這樣的

void copy(int array[ELEMENTS],int n)       //copying array elements and create linked list 
{ 
    struct node*temp = malloc(sizeof(struct node)); 
    temp->data=array[0]; 
    temp->next=NULL; 
    head =temp; 
    int i; 
    for(i=1;i<n;i++) 
    { 
     struct node*temp2= malloc(sizeof(struct node)); 
     temp->next= temp2; 
     temp2->data = array[i]; 
     temp2->next = NULL; 
     temp=temp2; 
    } 
} 

而且在打印過程中的變化while

while(temp!=NULL) 
    { 
     printf(" %d ",temp->data); 
     temp=temp->next; 

    } 
0

當你調用該函數的副本,你逝去的 「數組[ELEMENTS]」 作爲參數,但你只想傳遞「數組」。你傳遞的是你的數組之後的值,複製函數試圖將它解釋爲它實際期望的數組地址。

請注意,訪問一個不是你自己的值會導致未定義的行爲,並且實際上可能會使系統殺死你的應用程序。但是之後可能發生的情況是內存中會有0,它會傳遞給複製函數,然後嘗試訪問內存0x0至0xF處的值,這幾乎總是導致分段錯誤,正如您親身體驗的那樣,導致程序停止工作。

底線,刪除您要調用複製功能的行上的[ELEMENTS],我相信該程序應該開始工作。我懇請您儘管對指針進行進一步研究並將它們作爲函數參數傳遞。 (因爲我還沒有評論,我只是把它放在這裏,正如狙擊手所說的,你不必傳遞全局變量的引用,但他錯誤地認爲在函數結尾被破壞的結構是錯誤的。如果它是在堆棧中創建的,但是在堆中爲它分配空間,這意味着它將一直存在,直到你釋放()它或程序結束爲止。)

+0

此解決方案工作。它打印鏈表。謝謝。 – topcat