开发者

i can't hold old entries

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

void push(int p)
{
    static int i=0;
    int b;
    int *ptr =(int *)malloc((10)*sizeof(i开发者_开发问答nt));
    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);
    }
}

When i put new values , function is not hold old entries.I wait for your helps.


#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?
}


Each time you call push(), new memory is allocated to hold 10 integers. You are not doing anything to save the pointer to that memory.

This is called a memory leak, because you're allocating memory but you never free it. If you call push() enough times, you could run out of memory.


You must allocate only once. At the moment you are creating a memory leak each time you call the function push. Nobody refers to the memory once you leave the function. You can make it static to keep the information. Be aware that you are also limiting the number of values that you can hold at 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
}

Better yet you could pass in the location where you want to save the information.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜