Definition of the sequence table of "King's Way" (static allocation and dynamic allocation)

        One-dimensional arrays can be either statically allocated or dynamically allocated. However, during static allocation, since the array size and space have been fixed in advance, once the space is full, adding new data will cause overflow, which will cause the program to crash.

Static allocation method:

#include<stdio.h>
#define MaxSize 10   //定义表的最大长度 

typedef struct{
	int data[MaxSize];//顺序表的元素
	int length; //顺序表的当前长度  
}SqList;        //顺序表的类型定义

void InitList(SqList &L){
	 for(int i=0;i<MaxSize;i++){
	 	L.data[i]=0;  //给每个数组元素赋值为0
	 }
	 L.length=0;
}

int main(){
	SqList L;//声明一个顺序表
	InitList(L);//初始化一个顺序表
	for(int i=0;i<MaxSize;i++){
		printf("数组的第%d个元素:data[%d]=%d\n",i,i,L.data[i]);
	}
	return 0; 
}

operation result:

数组的第0个元素:data[0]=0
数组的第1个元素:data[1]=0
数组的第2个元素:data[2]=0
数组的第3个元素:data[3]=0
数组的第4个元素:data[4]=0
数组的第5个元素:data[5]=0
数组的第6个元素:data[6]=0
数组的第7个元素:data[7]=0
数组的第8个元素:data[8]=0
数组的第9个元素:data[9]=0
请按任意键继续. . .

Dynamic allocation method:

#include<stdio.h>
#include<stdlib.h>//包含malloc函数的头文件
#define InitSize 10 //表长度的初始定义

typedef struct{
	int  *data;//指示动态分配数组的指针
	int MaxSize,length; //数组的最大容量和当前个数
}SeqList; 
//初始化
void InitList(SeqList &L){
	//用malloc 函数申请一片连续的存储空间
	L.data =(int*)malloc(InitSize*sizeof(int)) ;
	L.length=0;
	L.MaxSize=InitSize;
    for(int i=0;i<L.MaxSize;i++){
	 	L.data[i]=0;  //将数组所有元素设置为0
	 }
} 

int main(void){
	SeqList L; //声明一个顺序表
	InitList(L);//初始化顺序表
	for(int i=0;i<L.MaxSize;i++){
		printf("数组的第%d个元素:data[%d]=%d\n",i,i,L.data[i]);
	}
	return 0; 
}

operation result:

数组的第0个元素:data[0]=0
数组的第1个元素:data[1]=0
数组的第2个元素:data[2]=0
数组的第3个元素:data[3]=0
数组的第4个元素:data[4]=0
数组的第5个元素:data[5]=0
数组的第6个元素:data[6]=0
数组的第7个元素:data[7]=0
数组的第8个元素:data[8]=0
数组的第9个元素:data[9]=0
请按任意键继续. . .

Guess you like

Origin blog.csdn.net/m0_59778008/article/details/131651263