From dc368f088a7692949c5f94fd723ddd4817f39867 Mon Sep 17 00:00:00 2001 From: jacekpoz Date: Sun, 10 Mar 2024 01:16:13 +0100 Subject: [PATCH] fix writing to the queue using the same value the fix was to memcpy the passed pointer to a local one and it works :-) --- lab01/zad1/include/queue.h | 2 +- lab01/zad1/src/main.c | 2 +- lab01/zad1/src/queue.c | 8 ++++++-- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/lab01/zad1/include/queue.h b/lab01/zad1/include/queue.h index a91dca8..9c8ecc4 100644 --- a/lab01/zad1/include/queue.h +++ b/lab01/zad1/include/queue.h @@ -6,7 +6,7 @@ typedef struct Queue Queue; -Queue *queue_new(size_t size); +Queue *queue_new(size_t size, size_t element_size); void *queue_read(Queue *queue); diff --git a/lab01/zad1/src/main.c b/lab01/zad1/src/main.c index c6f67b6..a1c6fc6 100644 --- a/lab01/zad1/src/main.c +++ b/lab01/zad1/src/main.c @@ -7,7 +7,7 @@ int main(void) { srand((unsigned int)time(NULL)); - Queue *q = queue_new(51); + Queue *q = queue_new(51, sizeof(long)); for (size_t i = 0; i < 50; ++i) { long val = rand() % 1000; diff --git a/lab01/zad1/src/queue.c b/lab01/zad1/src/queue.c index e97bb6f..20c12a5 100644 --- a/lab01/zad1/src/queue.c +++ b/lab01/zad1/src/queue.c @@ -1,19 +1,22 @@ #include #include +#include struct Queue { size_t back; size_t front; size_t size; + size_t element_size; void **data; }; -Queue *queue_new(size_t size) { +Queue *queue_new(size_t size, size_t element_size) { Queue *ret = malloc(sizeof(Queue)); ret->back = 0; ret->front = 0; ret->size = size; + ret->element_size = element_size; ret->data = malloc(size * sizeof(void*)); return ret; @@ -36,7 +39,8 @@ bool queue_write(Queue *q, void *value) { return false; } - q->data[q->back] = value; + void *local_value = memcpy(malloc(q->element_size), value, q->element_size); + q->data[q->back] = local_value; q->back = (q->back + 1) % q->size; return true;