[求助]关于内存分配的问题
#include<stdio.h>//#include<malloc.h>
#include<stdlib.h>
#define ADDLIST 10
#define LIST_INIT_SIZE 100
typedef struct
{
int *p;
int length; //表的长度
int listsize; // 表的实际大小
}*SqList;
void creatSqList(SqList r,int n)
{
int i;
int *q;
r->length = 0;
r->p = (int *)malloc(LIST_INIT_SIZE*sizeof(int));
q = r->p;
if(r->p == NULL) exit(0); //fail to assign storage
for(i=0;i<n;i++)
{
printf("输入第%d个值:",i);
scanf("%d",(r->p)++);
r->length++;
}
r->p = q;
r->listsize = LIST_INIT_SIZE; //assign size(at the begin)
}
/*void uniteSqList(SqList r1,SqList r2,SqList r3)
{
int r1_last,r2_last;
r3->listsize = r3->length = r1->length + r2->length;
r3->p = (int *)malloc(r3->listsize*sizeof(int));
if(r3->p==NULL)
{
printf("存储分配失败!");
exit(0);
}
r1_last = r1->p+r1->length - 1;
r2_last = r2->p+r2->length - 1;
while(r1->p<=r1_last && r2->p<=r2_last) //归并
{
if(*(r1->p)<*(r2->p)) *(r3->p)++ = *(r1->p)++;
else *(r3->p)++ = *(r2->p)++;
}
while(r1->p<=r1_last) //insert the rest of element of r1
*(r3->p++) = *r1->p++;
while(r2->p<=r2_last) //insert the rest of element of r1
*(r3->p++) = *r2->p++;
}*/
void outputSqList(SqList r)
{
int i;
for(i=0;i<r->length;i++,r->p++)
printf("%d",*r->p);
}
void destroyList(SqList r)
{
free(r->p);
}
//此例子只能输入2个有序递增的元素
int main()
{
SqList r1,r2,r3;
int n = 4; // size
printf("创建第一个线性表:\n");
creatSqList(r1,n); //n是线性顺序表的长度
outputSqList(r1);
printf("创建第二个线性表:\n");
//creatSqList(r2,n); //n是线性顺序表的长度
//uniteSqList(r1,r2,r3);
outputSqList(r1);
printf("\n");
//outputSqList(r2);
printf("\n");
//outputSqList(r3);
printf("\n");
//destroyList(r1);
//destroyList(r2);
//destroyList(r3);
system("pause");
return 0;
}
// 是不是 malloc 只能一次分配连续的内存, 多次分配就乱了地址呢?
有什么好的方法解决吗