回复 2楼 cnfarer
谢谢版主!原来的程序对IintList(Sqlist List)与InitList(Sqlist *List)理解有误,List在没有声明为全局变量时,IintList(Sqlist List)中的List为局部变量,同InsertList中的类似,List的值只在局部内改变,不能在全局中改变。故没有声明List为全局变量时,需要使用InitList(Sqlist *List)形式;如果声明List为全局变量,需要使用IintList(Sqlist List)的这种形式。注意局部变量和全局变量,注意指针和变量与区别。
下面列出本人的两种修改方法,与各位交流:
方法1:
#include <stdio.h>
#include <stdlib.h>
#define LIST_INIT_SIZE
10
#define LISTINCREMENT
10
#define OVERFLOW
0
#define OK
1
#define Empty
2
typedef int Elemtype;
typedef int Status;
typedef struct {
Elemtype *elem;
int length;
int listsize;
}Sqlist;
Sqlist List;
Status InitList()
{
List.elem = (Elemtype *)malloc(LIST_INIT_SIZE*sizeof(Elemtype));
if(!List.elem) exit(OVERFLOW);
List.length = 0;
List.listsize = LIST_INIT_SIZE;
return OK;
}
Status ListLength()
{
if(List.length == 0) return Empty;
else return List.length;
}
void ResizeList()
{
if(List.length >= List.listsize)
{
List.elem = (Elemtype *)realloc(List.elem,(LIST_INIT_SIZE + LISTINCREMENT)*sizeof(Elemtype));
List.length = List.length;
List.listsize = LIST_INIT_SIZE + LISTINCREMENT;
}
}
void InsertLastElem(Elemtype data)
{
if(List.length >= List.listsize)
{
ResizeList(List);
}
printf("List.length = %d,data = %d\r\n",List.length,data);
List.elem[List.length] = data;
List.length++;
printf("List.elem[%d] = %d\r\n",List.length-1,List.elem[List.length-1]);
}
void main()
{
int m,a[10]={1,2,3,4,5,6,7,8,9,10};
InitList(List);
for(m=0;m<10;m++)
{
InsertLastElem(a[m]);
}
printf("m = %d\r\n",ListLength(List));
}
方法2:
#include <stdio.h>
#include <stdlib.h>
#define LIST_INIT_SIZE
10
#define LISTINCREMENT
10
#define OVERFLOW
0
#define OK
1
#define Empty
2
typedef int Elemtype;
typedef int Status;
typedef struct{
Elemtype *elem;
int length;
int listsize;
}Sqlist;
Status InitList(Sqlist *List)
{
List->elem = (Elemtype *)malloc(LIST_INIT_SIZE*sizeof(Elemtype));
if(!List->elem) exit(OVERFLOW);
List->length = 0;
List->listsize = LIST_INIT_SIZE;
return OK;
}
Status ListLength(Sqlist *List)
{
if(List->length == 0) return Empty;
else return List->length;
}
void ResizeList(Sqlist *List)
{
if(List->length >= List->listsize)
{
Elemtype *p = (Elemtype *)realloc(List->elem,(LIST_INIT_SIZE + LISTINCREMENT)*sizeof(Elemtype));
List->elem = p;
List->length = LIST_INIT_SIZE;
List->listsize = LIST_INIT_SIZE + LISTINCREMENT;
}
}
void InsertLastElem(Sqlist *List,Elemtype data)
{
if(List->length >= List->listsize)
{
// ResizeList(List);
}
printf("List.length = %d,data = %d\r\n",List->length,data);
List->elem[List->length] = data;
List->length++;
printf("List.elem[%d] = %d\r\n",List->length,List->elem[List->length-1]);
}
void main()
{
int m,a[10]={1,2,3,4,5,6,7,8,9,10};
Sqlist List;
InitList(&List);
for(m=0;m<10;m++)
{
InsertLastElem(&List,a[m]);
}
printf("m = %d\r\n",ListLength(&List));
}