2014-03-19 61 views
-2

我是新的c编程,我的代码工作,但我的问题是,如果我在主函数中声明struct node *a,*b;,如何将ab传递到void create()。并且为什么它不工作,有人可以帮我理解它吗?如何在c中的main函数中声明struct变量?

#include<stdio.h> 
#include<conio.h> 
#include<malloc.h> 

struct node 
{ 
int d; 
struct node *next; 
}*start=NULL;struct node *a,*b; //move this part to main function -> struct node *a,*b; but its not working 

void create() 
{ 
    a=(struct node *)malloc(sizeof(struct node)); 
    printf("Enter the data : "); 
    scanf("%d",&a->d); 
    a->next=NULL; 

    if(start==NULL) 
    { 
     start=a; 
     b=a; 
    } 

    else 
    { 
     b->next=a; 
     b=a; 
    } 
} 

void display() 
{ 

    struct node *a; 
    printf("\nThe Linked List : "); 
    a=start; 

    while(a!=NULL) 
    { 
     printf("%d--->",a->d); 
     a=a->next; 
    } 
    printf("NULL\n"); 
} 



void main() 
{ 

    char ch; 

    do 
    { 
     create(); 
     printf("Do you want to create another : "); 
     ch=getche(); 
    } 

    while(ch!='n'); 

    display(); 

} 
void freenodes() 
{ 
    struct node *a; 
    a = start; 

    while(a != NULL) 
    { 
     struct node *freenode = a ; 
     a = a->next; 
     free(freenode) ; 
    } 
} 
+2

请定义你的 “不工作” 的意思。我们无法读懂你的想法。 –

+1

什么“不工作”? –

+0

也许读一些C教程? – zoska

回答

0
void main() 
{ 
    struct node name_of_varialbe;//this is struct variable declaration 
    ... 
}  
0

void create()原型只是改变void create(struct node *,struct node *)并调用这种方式:

char ch; 

do 
{ 
    struct node *a_main=(struct node *)malloc(sizeof(struct node)); 
    struct node *b_main=(struct node *)malloc(sizeof(struct node)); 
    create(a_main,b_main); 
    printf("Do you want to create another : "); 
    ch=getche(); 
}while(ch!='n'); 

void create(struct node *a,struct node *b) 
{ 
    //do your stuff 
} 
+0

你能解释你的代码吗? –

+0

@ R.A - 没有什么可以解释的 - 它简单地将参数传递给函数 - 参见我的编辑。 – Sadique