首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

,使用malloc分配内存后,不能给元素赋值的有关问题

2012-03-12 
求助,使用malloc分配内存后,不能给元素赋值的问题为什么我用malloc分配内存后,不能给元素赋值?显示 0x00ac

求助,使用malloc分配内存后,不能给元素赋值的问题
为什么我用malloc分配内存后,不能给元素赋值?
显示 0x00ac3749 处有未经处理的异常: 0xC0000005: 写入位置 0x00000000 时发生访问冲突。
第一个元素的值就写不进去,怎么回事?


L.elem=(ElemType *)malloc(MAXSIZE * sizeof(ElemType));
if(!L.elem) {printf("分配内存错误\n");exit(OVERFLOW);}
for(int i=0;i<MAXSIZE;i++)
{

L.elem[i]=i; //有错误

}

哪里出错了呢?

[解决办法]

C/C++ code
#include<stdio.h>#include<malloc.h>#include<stdlib.h>#define MAXSIZE 10#define OVERFLOW 1typedef int ElemType;struct {    ElemType* elem;}L;int main(){    int i;    L.elem=(ElemType *)malloc(MAXSIZE * sizeof(ElemType));    if(!L.elem) {printf("分配内存错误\n");exit(OVERFLOW);}    for(i=0;i<MAXSIZE;i++)    {                L.elem[i]=i;        printf("%d%s",i,(i!=MAXSIZE-1? " ":"\n"));            }    return 0;    }
[解决办法]
C/C++ code
Status InitList_Sq(SqList **L)    //这里                      //构造一个空的线性表{    (*L).elem=(ElemType *)malloc(MAXSIZE * sizeof(ElemType));    if((*L).elem==NULL)  {printf("分配内存错误\n");exit(OVERFLOW);}    (*L).length=0;    (*L).listsize=MAXSIZE;    return OK;}int main(void){    int k;    //SqList L={NULL,0,0};                 SqList L;    InitList_Sq(&L);               //这里    puts("建立空表成功");    for(int i=0;i<MAXSIZE;i++)    {                L.elem[i]=i;                                     }} 

热点排行