2017-03-23 37 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