关于指针在main中失效的有关问题
关于指针在main中失效的问题
自己谢了一个程序,是这样的:
#define Null 0
#define INF sizeof(struct information)
#include<stdlib.h>
#include<stdio.h>
struct information
{
int num;
int amo;
struct information *next;
};
struct information *creat(int n)
{
struct information *head=NULL,*p1,*p2;
head=p2=(struct information *)malloc(INF);
{
p1=(struct information*)malloc(INF);
p2->next=p1;
p2=p1;
}
p2->next=NULL;
return(head);
}
struct information *solve(struct information*head,struct information *info)
{
struct information *p3,*p4,*p5;
p3=head;
p5=info;
if(head==NULL)
{
head=p5;
p5->next=NULL;
}
else
{
while((p5->num>p3->num)&&(p3->next!=NULL))
{
p4=p3;p3=p3->next;
}
if (p5->num<=p3->num)
{
if(p5->num==p3->num)
p5->num=(p5->num+p5->num);
else p4->next=p5;
p5->next=p4;
}
else
{
p4->next=p5;p5->next=NULL;
}
}
return(head);
}
void main()
{
int a;
char answer,Y,N;
struct information *p;
information *creat();
printf("1.输入内容\n2.查看数据\n");
scanf("%d",&a);
if(a==1)
{
printf ("Input the number and amount\n");
scanf ("%d%d",&p3->num,&p3->amo);
printf("Continue? Y/N?\n");
scanf("%c",&answer);
while (answer=Y)
printf("%d,%d\n",p->num,p->amo);
p=p->next;
}
else
{
do
{
printf("%d %d\n",p->num,p->amo);
p=p->next;
}
while
(p!=NULL);
}
}
可是提示错误'p3' : undeclared identifier
有人告诉我这是因为p3在main中和之前定义不一样,那究竟要怎样改正呢?
------解决方案--------------------
p3在函数里定义,当然只在那个函数里才有效,主函数没效
要不就把p3定义成全局变量(这个不建议,尽量少用全局变量)
要不就利用函数参数把你要的数据送人函数里,再在函数里赋值给p3
自己谢了一个程序,是这样的:
#define Null 0
#define INF sizeof(struct information)
#include<stdlib.h>
#include<stdio.h>
struct information
{
int num;
int amo;
struct information *next;
};
struct information *creat(int n)
{
struct information *head=NULL,*p1,*p2;
head=p2=(struct information *)malloc(INF);
{
p1=(struct information*)malloc(INF);
p2->next=p1;
p2=p1;
}
p2->next=NULL;
return(head);
}
struct information *solve(struct information*head,struct information *info)
{
struct information *p3,*p4,*p5;
p3=head;
p5=info;
if(head==NULL)
{
head=p5;
p5->next=NULL;
}
else
{
while((p5->num>p3->num)&&(p3->next!=NULL))
{
p4=p3;p3=p3->next;
}
if (p5->num<=p3->num)
{
if(p5->num==p3->num)
p5->num=(p5->num+p5->num);
else p4->next=p5;
p5->next=p4;
}
else
{
p4->next=p5;p5->next=NULL;
}
}
return(head);
}
void main()
{
int a;
char answer,Y,N;
struct information *p;
information *creat();
printf("1.输入内容\n2.查看数据\n");
scanf("%d",&a);
if(a==1)
{
printf ("Input the number and amount\n");
scanf ("%d%d",&p3->num,&p3->amo);
printf("Continue? Y/N?\n");
scanf("%c",&answer);
while (answer=Y)
printf("%d,%d\n",p->num,p->amo);
p=p->next;
}
else
{
do
{
printf("%d %d\n",p->num,p->amo);
p=p->next;
}
while
(p!=NULL);
}
}
可是提示错误'p3' : undeclared identifier
有人告诉我这是因为p3在main中和之前定义不一样,那究竟要怎样改正呢?
------解决方案--------------------
p3在函数里定义,当然只在那个函数里才有效,主函数没效
要不就把p3定义成全局变量(这个不建议,尽量少用全局变量)
要不就利用函数参数把你要的数据送人函数里,再在函数里赋值给p3