线性表的插入问题

hpbykec 2007-09-18 08:30:42
以下是插入的程序,想知道为什么while运行两次之后,就不显示Input position,data了。
step了一下,发现到后面while语句里面把printf("Input position,data\n"); 给直接跳过了。
为什么会这样?!
谢谢!
/* Note:Your choice is C IDE */
#include <stdio.h>
#include <stdlib.h>
struct Data{
char *name;
int age;
int Size;
};
int Init_List(struct Data *New_Struct,int Max) /*申请空间*/
{
if((*New_Struct).name=(char *)malloc(sizeof(char *)*Max)==NULL)
{
printf("Init Failed\n");
return -1;
}
}
void Insert_List(struct Data *Des,int Position,char source) /*插入元素到指定位置之后*/
{
int i;
if(Position<=0)
Position=0;
if(Position>Des->Size)
Position=Des->Size;
for(i=(*Des).Size+1;i>Position;i--)
{
*((*Des).name+i)=*((*Des).name+i-1);
}
*((*Des).name+Position)=source;
Des->Size++;
}
main()
{
int d,Max=20;
char s,G='y';
struct Data *p;
Init_List(&p,Max);
p->Size=0; /*初始化*/
p->name="\0";
while(G=='y')
{
printf("Input position,data\n");
scanf("%d %c",&d,&s);
Insert_List(p,d,s);
printf("%s\t%d\n",p->name,p->Size);
printf("Continue?y,n\n");
G=getch();
}
free(p->name);
}
...全文
240 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
hpbykec 2007-09-19
  • 打赏
  • 举报
回复
不好意思,贴出来的不是最后保存的程序,在这里向各位说声对不起。
manrenmanren(蛮人) 由于优先级的关系,那个括号时可以不用加的,当然加了更好,可读性增强。
下面这段程序时可以运行的,但就是运行两个循环之后,再输入‘y’,它就不显示
“Input position,data”,直接跳到scanf("%d %c",&d,&s);直接输入连个参数,还可以继续运行,而且插入结果正确。再输入‘y’又进入下一循环,还是没有提示“Input sition,data”。
不知道为什么。

/* Note:Your choice is C IDE */
#include <stdio.h>
#include <stdlib.h>
struct Data{
char *name;
int age;
int Size;
};
int Init_List(struct Data *New_Struct,int Max) /*动态申请空间*/
{
if((*New_Struct).name=(char *)malloc(sizeof(char *)*Max)==NULL)
{
printf("Init Failed\n");
return -1;
}
return 1;
}
void Insert_List(struct Data *Des,int Position,char source)
{
int i;
if(Position<=0)
Position=0;
if(Position>Des->Size)
Position=Des->Size;
for(i=(*Des).Size+1;i>Position;i--)
{
*((*Des).name+i)=*((*Des).name+i-1);
}
*((*Des).name+Position)=source;
Des->Size++;
}
main()
{
int d,Max=20;
char s,G='y';
struct Data *p;
Init_List(&p,Max);
p->Size=0; /*初始化*/
p->name="\0";
while(G=='y')
{
printf("Input position,data\n");
scanf("%d %c",&d,&s);
Insert_List(p,d,s);
printf("%s\t%d\n",p->name,p->Size);
printf("Continue?y,n\n");
G=getch();
}
free(p->name);
}
huhaihong 2007-09-18
  • 打赏
  • 举报
回复
楼上正解
manrenmanren 2007-09-18
  • 打赏
  • 举报
回复
这一行少括号 if((*New_Struct).name=(char *)malloc(sizeof(char *)*Max)==NULL)

是不是应该这样
if(((*New_Struct).name = (char *)malloc(sizeof(char *)*Max))==NULL)
manrenmanren 2007-09-18
  • 打赏
  • 举报
回复
这一行 有问题啊Init_List(&p,Max);
是不是应该这样
Init_List(p,Max);

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧