数据结构中顺序表的问题

Tody Guo 2008-09-16 08:23:41

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define ERROR 0
#define OK 1

struct STU{
char name[20];
char stuno[10];
int age;
int score;
}stu[50];
struct LIST
{
struct STU stu[50];
int length;
}L;

int printlist(struct LIST L)
{
int i;
printf("name stuno age score\n");
for(i=0;i<L.length;i++)
printf("%s %s\t%d\t%d\n", L.stu[i].name, L.stu[i].stuno,L.stu[i].age, L.stu[i].score);
printf("\n");
}

int listinsert(struct LIST *L,int i,struct STU e)
{
struct STU *p,*q;
if (i<1||i>L->length+1) return ERROR;
q=&(L->stu[i-1]);
for(p=&L->stu[L->length-1];p>=q;--p)
{
*(p+1)=*p;
}
*q=e;
++L->length;
return OK;
}


main()
{
struct STU e;
L.length=0;

strcpy(e.name,"zmofun");
strcpy(e.stuno,"100001");
e.age=80;
e.score=1000;
listinsert(&L,1,e);

printlist(L);
printf("List length now is %d.\n\n",L.length);

strcpy(e.name,"bobjin");
strcpy(e.stuno,"100002");
e.age=80;
e.score=1000;
listinsert(&L,1,e);

printlist(L);
printf("List length now is %d.\n\n",L.length);
}


其中 for(p=&L->stu[L->length-1];p>=q;--p)的红色的那个部分在i=1和L->length为0时(也就是在第一次插入记录时),p是否已经越界了?因为这个时候p=&L->stu[-1]。
...全文
110 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Tody Guo 2008-09-20
  • 打赏
  • 举报
回复

是,这样的,但是为什么要这样定义呢?
这样的问题是我在《数据结构》里面看到的,他讲了这个例子,具体为什么要这样就不清楚了。
谁人能知阿?
K行天下 2008-09-16
  • 打赏
  • 举报
回复
一开始这个循环不执行

70,022

社区成员

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

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