tags:

views:

60

answers:

1

where is the mistake?

My code here:

 typedef struct _box
    {
        char *dados;
        struct _box * proximo;
    } Box;

    typedef struct _pilha
    {
        Box * topo;
    }Stack;

void Push(Stack *p, char * algo)
{
    Box *caixa;
    if (!p)
    {
        exit(1);
    }

    caixa = (Box *) calloc(1, sizeof(Box));
    caixa->dados = algo;
    caixa->proximo = p->topo;
    p->topo = caixa;
}


char * Pop(Stack *p)
{
    Box *novo_topo;
    char * dados;
    if (!p)
    {
        exit(1);
    }

    if (p->topo==NULL)
        return NULL;

    novo_topo = p->topo->proximo;

    dados = p->topo->dados;

    free(p->topo);
    p->topo = novo_topo;

    return dados;
}


void StackDestroy(Stack *p)
{
    char * c;
    if (!p)
    {
        exit(1);
    }
    c = NULL;
    while ((c = Pop(p)) != NULL)
    {
        free(c);
    }
    free(p);
}

int main()
{
int conjunto = 1;
char p[30], * v;
int flag = 0;

Stack *pilha = (Stack *) calloc(1, sizeof(Stack));

FILE* arquivoIN = fopen("L1Q3.in","r");
FILE* arquivoOUT = fopen("L1Q3.out","w");

if (arquivoIN == NULL)
{
    printf("Erro na leitura do arquivo!\n\n");
    exit(1);
}

fprintf(arquivoOUT,"Conjunto #%d\n",conjunto);

while (fscanf(arquivoIN,"%s", p) != EOF )
{
    if (pilha->topo == NULL && flag != 0)
    {
        conjunto++;
        fprintf(arquivoOUT,"\nConjunto #%d\n",conjunto);
    }

    if(strcmp(p, "return") != 0)
    {
        Push(pilha, p);
    }

    else
    {
        v = Pop(pilha);

        if(v != NULL)
        {
            fprintf(arquivoOUT, "%s\n", v);
        }
    }
    flag = 1;
}

StackDestroy(pilha);

return 0;

}

The Pop function returns the string value read from file. But is not correct and i don't know why.

+3  A: 

You're not allocating any storage for the strings pointed to by dados - you're just re-using one string buffer (p) and passing that around, so all your stack elements just point to this one string.

Paul R
Yes, exactly. The `Box` objects that you're storing in the stack contain `char *` pointers -- they don't actually contain the strings themselves. So, you create a `Box` pushed onto the stack, and it points to where `p` is, and then you change `p` in reading the next value, and since the `Box` already on the stack is still pointing to `p`, it's now pointing at the changed value.
Brooks Moses
Oh my god!thank you very much!=DI have had spent many time with this problem, must be the lack of caffeine =)
Andersson Melo