顺序表初始化有长度限制吗,怎么回事啊

pi6pi6 2005-09-19 05:10:51
#define LIST_INIT_SIZE 50 // 线性表存储空间的初始分配量
这里把它设为58就运行出错,为什么?
示例
#include<string.h>
#include<process.h> /* exit() */
#include<stdio.h> /* EOF(=^Z或F6),NULL */
#include<malloc.h> /* malloc()等 */
#define LIST_INIT_SIZE 50 // 线性表存储空间的初始分配量 这里把它设为58就运行出错,为什么?
#define LIST_INCREMENT 1 /* 线性表存储空间的分配增量 */




typedef struct
{
char *name[10];
char *phonenum[15];
int length;
int listsize;
}dhbsList;

void InitList(dhbsList *la)
{
int i;
for(i=0; i<LIST_INIT_SIZE; ++i){
la->name [i]=(char*)malloc(10*sizeof(char));
if(!la->name[i] ) {printf(" 操作失败! \n");exit(-2); }
}
for(i=0; i<LIST_INIT_SIZE; ++i){
la->phonenum [i]=(char*)malloc(15*sizeof(char));
if(!la->phonenum [i]) { printf(" 操作失败! \n");exit(-2); }
}
la->length=0;
la->listsize=LIST_INIT_SIZE;

}

void main(){
int i;
dhbsList L;
InitList(&L);
i=0;
printf("%d",i);

}



高人出手啊!!
...全文
197 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
pi6pi6 2005-09-19
  • 打赏
  • 举报
回复
我采用的是笨办法,
Status ListInsert(dhbsList *L,char *elem1,char *elem2)
{ /* 初始条件:顺序线性表L已存在,1≤i≤ListLength(L)+1 */

int i; dhbsList la;
if((*L).length>=(*L).listsize) /* 当前存储空间已满,增加分配 */
{
for(i=0; i<LIST_INIT_SIZE+LIST_INCREMENT; ++i){
la.name [i]=(char*)malloc(10*sizeof(char));
if(!la.name[i] ) exit(-2); /* 存储分配失败 */
}
for(i=0; i<LIST_INIT_SIZE+LIST_INCREMENT; ++i){
la.phonenum [i]=(char*)malloc(15*sizeof(char));
if(!la.phonenum [i]) exit(-2); /* 存储分配失败 */
}
la.length=(*L).length ;
la.listsize=(*L).listsize +LIST_INIT_SIZE;
for(i=0; i<(*L).length ; ++i){
strcpy( la.name[i],(*L).name [i]);
strcpy( la.phonenum [i],(*L).phonenum [i]);
}
*L=la;//传过来地址,改变地址指向的值
}

strcpy((*L).name[(*L).length],elem1); /* 插入elem */
strcpy((*L).phonenum[(*L).length],elem2); /* 插入elem2 */
++(*L).length; /* 表长增1 */
printf(" 输入数据成功! \n");
return OK;
}

并且不知道何时free()?!
pi6pi6 2005-09-19
  • 打赏
  • 举报
回复
高手好事做到底,
char *name[LIST_INIT_SIZE];
char *phonenum[LIST_INIT_SIZE+5];

在需要增加容量的时候,指针数组如何realloc()啊
pi6pi6 2005-09-19
  • 打赏
  • 举报
回复
哦,晕了,的确应该这样:char *name[LIST_INIT_SIZE];
char *phonenum[LIST_INIT_SIZE+5];
lander9999 2005-09-19
  • 打赏
  • 举报
回复
内存越界!

char *name[10];
char *phonenum[15];

#define LIST_INIT_SIZE 50 // 线性表存储空间的初始分配量

for(i=0; i<LIST_INIT_SIZE; ++i)
la->name [i]=(char*)malloc(10*sizeof(char));
数组越界!

zhouhuahai 2005-09-19
  • 打赏
  • 举报
回复
还有一个问题, malloc的指针,应该要记得free掉.
zhouhuahai 2005-09-19
  • 打赏
  • 举报
回复
typedef struct
{
char *name[10];
char *phonenum[15];
int length;
int listsize;
}dhbsList;

你的结构体中的成员name是个指针数组, 只有10个元素,每个元素是char *.

for(i=0; i<LIST_INIT_SIZE; ++i){
la->name [i]=(char*)malloc(10*sizeof(char));
这里LIST_INIT_SIZE只要大于10就越界了.
后面的la->phonenum 也是一样.

建议修改成:
typedef struct
{
char *name[LIST_INIT_SIZE];
char *phonenum[LIST_INIT_SIZE+5];
int length;
int listsize;
}dhbsList;
pi6pi6 2005-09-19
  • 打赏
  • 举报
回复
up

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧