2016-03-29 4 views
0

私は現時点で勉強しようとしていますが、私に送られたファイルは正しくありません。私はいくつかの問題を修正しようとしましたが、それが始まりました。私は動的な記憶を学んでいるので、私はそれを知らない。 realloc()のコードは次のとおりです。ダイナミックメモリの新機能。 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; 

} 
+0

コードのコメントのようになります。 –

答えて

0

あなたが持っていたいくつかの問題ここ

  • カウントが最初の反復で1 Overwiseで始まる必要があり、最終的に同じメモリチャンクの自由

    1. ダブルあなたはのサイズを変更してみてください0バイトのメモリブロック
    2. アウトオブバンド境界エラー 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; 
    
    }