I am working on an assignment in which I can not modify main. I am trying to create a ringbuffer module so that the main program can call multiple ringbuffers at a time (it is actually multi-threaded, but that doesn't matter yet.) I am tring to create a ringbuf_alloc function that initializes the ringbuf-t struct and passes back the pointer to the ringbuf_t struct. However I am getting stuck on passing the pointer. I can't make it a local variable, because it changes each time I call it, and I can't make it a static variable because it changes each time a new buffer calls it. Appreciate any help or any ideas:
Code:
Code:
Ringbuf_t Typedef:
typedef struct ringbuf {
int size; /* # of valid elements in the buffer */
int head; /* head pointer */
int tail; /* tail poiner */
int capacity;
int *buf;
} ringbuf_t;
Main:
ringbuf_t *ringbuf1 = NULL;
ringbuf_t *ringbuf2 = NULL;
n = 10;
if((ringbuf1 = ringbuf_alloc(n)) == NULL)
syserr("test 1 ringbuf_alloc 2");
n = 20;
if((ringbuf2 = ringbuf_alloc(n)) == NULL)
syserr("test 1 ringbuf_alloc 3");
if(ringbuf_get_capacity(ringbuf1) != 10 ||
ringbuf_get_capacity(ringbuf2) != 20)
printf("logic error 7\n");
Ringbuf_alloc function
static ringbuf_t p, rb;
ringbuf_t
*ringbuf_alloc(int capacity)
{
if (pthread_mutex_init(&mtx, NULL))
syserr("pthread_mutex_init");
p.capacity = capacity;
p.size = 0;
p.head = 0;
p.tail = 0;
p.buf=(int *) malloc(sizeof(int)*capacity);
return &p;
}