【问题标题】:How to declare struct variable with in the main function in c?如何在c的主函数中声明结构变量?
【发布时间】:2014-04-25 13:10:06
【问题描述】:

我是 c 编程的新手,我的代码正在运行,但我的问题是,如果我在 main 函数中声明 struct node *a,*b;,如何将 ab 传递给 void create()。为什么它不起作用,有人可以帮我理解吗?

#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) ;
    }
}

【问题讨论】:

  • 请定义您所说的“不工作”是什么意思。我们无法读懂你的想法。
  • 什么“不工作”?
  • 也许读过一些 C 教程?

标签: c parameter-passing


【解决方案1】:
void main()
{
  struct node name_of_varialbe;//this is struct variable declaration
  ...
}    

【讨论】:

    【解决方案2】:

    只需将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
    }
    

    【讨论】:

    • @R.A - 没什么好解释的 - 将参数简单地传递给函数 - 请参阅我的编辑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    相关资源
    最近更新 更多