【问题标题】:New in dynamic memory. realloc ();动态内存中的新功能。重新分配();
【发布时间】:2016-03-29 06:47:53
【问题描述】:

我现在正在努力学习,但发送给我的文件不正确。我试着修复了几件事,但它开始了,然后它就崩溃了。我正在学习动态记忆,所以我不知道。这里是realloc()的代码;

 #include <stdio.h> /* printf, scanf, NULL */

    #include <stdlib.h> /* malloc, free, rand */

    int main ()

{

 int count=0,i;

 int *stations=NULL,*ptrToStations=NULL;



for(i=1;i<=7;i++,count++)
    {

ptrToStations=(int*)realloc(stations,count*sizeof(int));

if(ptrToStations!=NULL)//заделили сме памет

 { stations = ptrToStations;

 ptrToStations[count]=i;}

    }

for(i=0;i<7;i++)

printf("%d",stations[i]);

printf("\n");



//добавяне на 8 елемент

ptrToStations=(int*)realloc(stations,++count*sizeof(int));

if(ptrToStations!=NULL)//заделили сме памет

 { stations = ptrToStations;

 ptrToStations [count-1]=count;}



 for(i=0;i<count;i++)

printf("%d",stations[i]);

printf("\n");

int x=3;

//преместваме елементите с един назад

for(i=x;i<count;i++)


ptrToStations[i-1]=ptrToStations[i];

//премахване на 8 елемент

ptrToStations=(int*)realloc(stations,--count*sizeof(int));

if(ptrToStations!=NULL)//заделили сме памет



 stations = ptrToStations;



for(i=0;i<count;i++)


printf("%d",stations[i]);

printf("\n");


 free (ptrToStations);

 free (stations);

 return 0;

}

【问题讨论】:

  • 代码 cmets 应该是英文

标签: dynamic realloc


【解决方案1】:

你在这里遇到了几个问题

  1. 最终双释放相同的内存块
  2. count 应该从 1 开始。在第一次迭代中,您尝试将内存块的大小更改为 0 字节
  3. 超出数组绑定错误 ptrToStations[count]=i;

您的代码实际上应该是这样的

#include <stdio.h> /* printf, scanf, NULL */

    #include <stdlib.h> /* malloc, free, rand */

    int main ()

{

 int count=1,i;

 int *stations=NULL,*ptrToStations=NULL;



for(i=1;i<=7;i++,count++){

    ptrToStations=(int*)realloc(stations,count*sizeof(int));

    if(ptrToStations != NULL) { 
        stations = ptrToStations;
        ptrToStations[count-1]=i;
        for(i=0;i<count;i++)
            printf("%d",stations[i]);
        printf("\n");
    }
}





//добавяне на 8 елемент

ptrToStations=(int*)realloc(stations,++count*sizeof(int));

if(ptrToStations!=NULL){ 
    stations = ptrToStations;
    ptrToStations [count-1]=count;
    }



 for(i=0;i<count;i++)
    printf("%d",stations[i]);
printf("\n");

int x=3;

//преместваме елементите с един назад

for(i=x;i<count;i++)
    ptrToStations[i-1]=ptrToStations[i];

//премахване на 8 елемент

ptrToStations=(int*)realloc(stations,--count*sizeof(int));

if(ptrToStations!=NULL) {
    stations = ptrToStations;
    for(i=0;i<count;i++)
        printf("%d",stations[i]);
printf("\n");
}


 free (stations);

 return 0;

}

【讨论】:

    猜你喜欢
    • 2020-04-22
    • 2011-12-01
    • 2017-12-03
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多