realloc problem on compilation | Sololearn: Learn to code for FREE!

+2

realloc problem on compilation

hello. I am trying to implement queues in C. I wrote this as queue.h: ``` typedef struct { void * arr[1]; int len, head, tail; } queue; ``` and, in test.c: ``` #include <stdio.h> #include <stdlib.h> #include "queue.h" queue spawn(int len){ queue q; q.arr = (void *) realloc(q.arr, len * sizeof(void *)); /* = (void *) realloc(...);*/ for(int i = 0; i < len; i++){ q.arr[i] = NULL; } q.len = len, q.head = 0, q.tail = 0; return q; } ``` But, when I runned gcc, i got: ``` error: assignment to expression with array type q.arr = (void *) realloc(q.arr, len * sizeof(void *)); ``` I began reading this post: https://stackoverflow.com/questions/37225244/error-assignment-to-expression-with-array-type-error-when-i-assign-a-struct-f But it doesn't answer my problem. I tthink i did everything right tho, as I saw in the C course and here: https://www.tutorialspoint.com/c_standard_library/c_function_realloc.htm but it seems that I didn't. What must I do?

10/15/2020 8:54:13 AM

Gwlanbzh

4 Answers

New Answer

+1

I tried changing the following q.arr = To q.arr[0] = Or *q.arr = And now gcc compiles that piece of code without errors. q.arr its just an address it cant hold any value q.arr[0] is a pointer variable which can hold an address that why it can recieve the address from the realloc function. *q.arr targets the content of that address which is a pointer variable. *q.arr is same as q.arr[0] That array of pointers + structs + memory allocation is still tricky to me I need to study and practice more, it requires solid foundation. 😥 I hope some advanced C coders take a look at your problem. Good luck mate!

+1

@arturop I'm implementing the queue as an array of void pointers. But with what you suggest me, the code would be changed: my aim is here to give the queue a non-default size, while what you do is something completely different. Thanks tho for answering!

0

Gwlanbzh 😅✌