2010-12-20 32 views
0
#include <stdio.h> 
#include <stdlib.h> 

void push(int p) 
{ 
    static int i=0; 
    int b; 
    int *ptr =(int *)malloc((10)*sizeof(int)); 
    ptr[i]=p; 
    for(b=0;b<=i;b++){ 
    printf("%d",ptr[b]); 
    printf("\n"); 
    } 
    i++; 
} 
int main() 
{ 
    int a; 
    while(1) 
    { 
    scanf("%d",&a); 
    push(a); 
    } 
} 

當我把新的價值觀,功能不是舊的entries.I等待你的幫助。我不能容納舊的條目

+1

製作PTR靜態的,只能一次分配它。 – 2010-12-20 14:33:55

+0

請學習使用代碼標記('{}')來清晰地格式化和突出顯示您的代碼。 – MAK 2010-12-20 14:37:49

回答

1

每次調用push()時,都會分配新內存來保存10個整數。你沒有做任何事情來保存指向那個內存的指針。

這被稱爲內存泄漏,因爲你正在分配內存,但你永遠不會釋放它。如果你足夠多次調用push(),你可能會用完內存。

1

您只能分配一次。目前你每次調用函數push時都會產生內存泄漏。一旦離開功能,沒有人會提到記憶。您可以使其保持靜態以保持信息。要知道,你也限制了你可以在10

void push(int p) 
{ 
    static int i=0; 
    static int *ptr =(int *)malloc((10)*sizeof(int)); // To keep the values 
    int b; 
    ptr[i]=p; 
    for(b=0;b<=i;b++){ 
     printf("%d",ptr[b]); 
     printf("\n"); 
    } 
    i++; 
    if(i >= 10) i = 0; // To make sure there is no overflow 
} 

持有更重要的是,你可以通過在你要保存信息的位置值的數量。

void push(int p, int *ptr) 
{ 
    static int i=0; 
    int b; 
    ptr[i] = b; 
    for(b=0;b<=i;b++){ 
     printf("%d",ptr[b]); 
     printf("\n"); 
    } 
    i++; 
    if(i >= 10) i = 0; // To make sure there is no overflow 
} 
int main() 
{ 
    int a; 
    int values[10]; 
    while(1) 
    { 
     scanf("%d",&a); 
     push(a, values); 
    } 
} 
+0

有沒有必要更復雜它。但它說得很好。 – karlphillip 2010-12-20 14:45:27

+0

這些解決我的問題,但我必須使用malloc和realloc這個問題。當使用static int * ptr =(int *)malloc((10)* sizeof(int));我犯了一個錯誤 – justuser 2010-12-20 15:34:16

2
#include <stdio.h> 
#include <stdlib.h> 

void push(int p) 
{ 
    static int i = 0; 
    static int ptr[10]; // since you are NOT freeing this memory later, 
         // there's no need to use malloc. 
    ptr[i] = p; 

    int b; 
    for (b = 0; b <= i; b++) 
    { 
     printf("ptr[%d] --> %d\n", b, ptr[b]); 
    } 

    printf("\n"); 

    i++; 
} 

int main() 
{ 
    int a; 
    while(1) 
    { 
     scanf("%d",&a); 
     push(a); 
    } 

    return 0; // main() expects you to return something, remember? 
}