对结构体动态初始化的问题
程序代码:
#include <stdio.h> #include <stdlib.h> #define MaxSize 100 typedef int Elemtype; typedef struct SqList { Elemtype data[MaxSize]; int length; //顺序表的长度 }; void Init__List(struct SqList *sq); int Length__List(struct SqList sq); Elemtype Get__List(struct SqList sq, int index); int Locate__List(struct SqList sq, int value); void Insert__List(struct SqList*sq,int index,int value); void Delete__List(struct SqList *sq, int index); int main(void) { struct SqList sq; Init__List(&sq); printf("线性表的长度是%d\n", sq.length); system("pause"); return 0; } void Init__List(struct SqList *sq) { //sq = (struct SqList *)malloc(sizeof(struct SqList)); 问题:只有把这句注释了,上面的长度是0,否则是垃圾值,是为啥呢 sq->length = 0; } /* typedef struct SqList { Elemtype data[MaxSize]; int length; //顺序表的长度 }; */ //求顺序表的长度 int Length__List(struct SqList sq) { return sq.length; } /* 返回线性表L中的第i个元素的值或地址 */ Elemtype Get__List(struct SqList sq, int index) { if (index <= 0 || index > sq.length) { return -1; //-1表示不存在 } return sq.data[index - 1]; } int Locate__List(struct SqList sq, int value) { for (int i = 1; i <= sq.length; i++) { if (sq.data[i - 1] == value) { return i - 1; } } return -1; } void Insert__List(struct SqList*sq,int index,int value) { if (index <= 0 || index > sq->length + 1) { printf("插入的位置错误\n"); } for (int i = sq->length - 1; i >= index - 1; i--) { sq->data[i + 1] = sq->data[i]; } sq->data[index - 1] = value; sq->length++; } void Delete__List(struct SqList *sq, int index) { if (index <= 0 || index > sq->length) { printf("删除的位置错误\n"); } for (int i = index - 1; i < sq->length; i++) { sq->data[i] = sq->data[i + 1]; } sq->length--; }