昨晚的编程问题追问。。

/*
18 16 14 12 10 8 6 4 2 0
L->elem[5] = 8
Press any key to continue
*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

//函数结果状态代码
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status; //函数的返回值
typedef int ElemType; //线性表元素定义

//#define LIST_INIT_SIZE 100 //线性表存储空间的初始分配量
//#define LISTINCREMENT 10 //线性表存储空间的分配增量
#define LIST_INIT_SIZE 5 //线性表存储空间的初始分配量
#define LISTINCREMENT 2 //线性表存储空间的分配增量
typedef struct Sq {
ElemType *elem; //存储空间基址
int length; //当前长度
int listsize; //当前分配的存储容量(以sizeof(ElemType)为单位)
}SqList;

Status InitList_Sq(SqList *L) { // 构造一个空的线性表L。
L->elem = (ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if (!L->elem) return OVERFLOW; // 存储分配失败
L->length = 0; // 空表长度为0
L->listsize = LIST_INIT_SIZE; // 初始存储容量
return OK;
}

Status ListInsert_Sq(SqList *L,int i,ElemType e) { //在顺序线性表L中第i个位置之前插入新的元素e
//i的合法值为1 < i < ListLength_Sq(L) - 1
ElemType *newbase;
ElemType *q;
ElemType *p;
if(i < 1 || i > L->length + 1) return ERROR; //i的值不合法
if(L->length >= L->listsize) { //当前存储空间已满,增加分配
newbase = (ElemType *)realloc(L->elem,(L->listsize + LISTINCREMENT)*sizeof(ElemType));
if(!newbase) //存储分配失败
return OVERFLOW;
L->elem = newbase; //新基址
L->listsize += LISTINCREMENT; //增加存储容量
}
q = &(L->elem[i - 1]); //q为插入的位置
for(p = &(L->elem[L->length - 1]); p >= q; --p) {
*(p + 1) = *p; //插入位置及之后的元素右移
}
*q = e; //插入e
++ L->length; //表长增1
return OK;
}

void main() {
int i;
SqList *L = (SqList *)malloc(sizeof(Sq)); // L未定义时,Elem指针保存在哪儿?
InitList_Sq(L);
for(i = 0; i < 10; ++i)
ListInsert_Sq( L,1,2 * i);
for(i = 0; i < 10; ++i) printf("%d ",L->elem[i]);
printf("\n");
printf("L->elem[5] = %d\n",L->elem[5]);
}
为什么要调用malloc函数给*L分配内存呢?不是SqList *L;这句就能使系统自动分配内存给*L吗?就像int a就能使系统自动分配内存给a。

在前一个的回答的评论中已经说过了。
任何类型数据指针在声明以后,其指向的位置是随机的,只有初始化或赋值以后,才能对该指针指向的内容进行下一步的操作。来自:求助得到的回答
温馨提示:答案为网友推荐,仅供参考
相似回答