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

/* Report an error and abort */
#define FATAL_ERROR(message)                        \
  {                                 \
    fprintf(stderr,"In %s(%d) [function %s]: %s\n",         \
        __FILE__, __LINE__, __FUNCTION__ , (message)  );        \
    abort();                                \
  }                                 \

/* Report a posix error (similar to perror) and abort */
#define FATAL_PERROR(errcode) FATAL_ERROR(strerror(errcode))

void* Malloc(size_t n)
{
  void* new = malloc(n);
  if(new==NULL) FATAL_ERROR("Out of memory.");
  return new;
}



typedef struct twit{
    char data[141];               //contains the actual data
    //struct twit *prev;      //pointer to previous node (Closer to front)
    struct twit *next;      //pointer to next node (Closer to back)
}twit;

typedef struct twitbuffer{
    twit *first;
    twit *last;
    int size;
}twit_buffer;

/*
   function for create a new buffer
*/
void new_twitbuffer(twit_buffer *a)
{
    a=Malloc(sizeof(twit)*12000);
    a->first = a->last = NULL;
    a->size = 0;
    return;
}

int twitbuffer_empty(twit_buffer *a) {
    if(a->first == NULL)
        return 1;
    else
        return 0;
}


/*
   function to insert a new twit in the buffer
*/
void insertTwit(twit_buffer *a, char *data)
{
    twit new;
    if (strlen(&data)<=140){
        strcpy(&new.data,data);
    }
    else{
        printf("Twit > 140 characters...");
    }
    if (new.data == NULL) {
            //errno = ENOMEM;
        printf("error!");
            return;
    }

    if(a->first==NULL){
        a->first = a->last = &new;
    }else{
        a->last->next=&new;
        a->last=&new;
    }
    new.next= NULL;
    a->size++;
    return;
}

char* popTwit(twit_buffer *a) {
    if (twitbuffer_empty(a)) {
        return NULL;
    }
    char *data;
    //strcpy(&data,a->first->data);
    data=a->first->data;
    if (a->first == a->last)
        a->first = a->last = NULL;
    else
        a->first = a->first->next;
    a->size--;
    return data;
}

twit_buffer mytwitbuffer;


int main()
{
    new_twitbuffer(&mytwitbuffer);

    //printf("a=%d",mytwitbuffer);

    char *a = "first twit\n";
    char *b = "second twit\n";
    char *c = "third twit\n";

    insertTwit(&mytwitbuffer, a);
    insertTwit(&mytwitbuffer, b);
    insertTwit(&mytwitbuffer, c);

    char *poppp;
    poppp = popTwit(&mytwitbuffer);
    printf("%s", poppp);

    poppp = popTwit(&mytwitbuffer);
    printf("%s", poppp);

    poppp = popTwit(&mytwitbuffer);
     printf("%s", poppp);
}

这是我实现队列的代码。当我执行这个我得到这个结果:

thir�it
(null)(null)

这意味着前两次插入没有正确完成,第三次以“超自然”方式进入标准输出!你有什么想法?

4

1 回答 1

4

您正在 twit 缓冲区中存储对局部变量“new”的引用。你应该 Malloc 它,而不是在本地声明它

于 2013-01-11T07:45:21.570 回答