C 新手:在数组中存储结构
我的第一个 C 作业是创建一个队列。我使用的是基于数组的实现,而不是链表。
当我尝试编译我的代码时,出现以下错误:
Queue.c: In function 'Enqueue':
Queue.c:23: warning: assignment from incompatible pointer type
这是我的代码,如果需要,我将提供标头代码:
#include "QueueElement.h"
#include "Queue.h"
#define QUEUE_SIZE 10
struct QueueStruct {
QueueElement *contents[QUEUE_SIZE];
int size;
};
Queue CreateQueue(void) {
Queue q = malloc(sizeof(struct QueueStruct));
q->size = 0;
return q;
}
void DestroyQueue(Queue q) {
free(q);
}
void Enqueue(Queue q, QueueElement *e) {
if (q->size < QUEUE_SIZE) {
q->contents[q->size++] = *e; /* PROBLEM IS HERE */
}
}
非常感谢有关此问题的任何帮助以及任何其他建议。 谢谢你们。
My first C assignment is to create a Queue. I am using an array based implementation as opposed to a linked list.
I am getting the following error when I try to compile my code:
Queue.c: In function 'Enqueue':
Queue.c:23: warning: assignment from incompatible pointer type
Here is my code, I will supply the header code if needed:
#include "QueueElement.h"
#include "Queue.h"
#define QUEUE_SIZE 10
struct QueueStruct {
QueueElement *contents[QUEUE_SIZE];
int size;
};
Queue CreateQueue(void) {
Queue q = malloc(sizeof(struct QueueStruct));
q->size = 0;
return q;
}
void DestroyQueue(Queue q) {
free(q);
}
void Enqueue(Queue q, QueueElement *e) {
if (q->size < QUEUE_SIZE) {
q->contents[q->size++] = *e; /* PROBLEM IS HERE */
}
}
Any help with this problem is greatly appreciated as well as any other suggestions.
Thanks guys.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我相信你的意思是
(没有星号)
因为您要将 QueueElement* 类型的内容分配给 QueueElement*[] 数组。
或者你也许可以通过改变它来修复它 - 这可能更接近我认为你可能的意思: -
不确定这是否有意义/我是对的。
I believe you mean
(Without the asterisks)
because you're assigning something of type QueueElement* to an array of QueueElement*[].
or you might be able to fix it by changing this instead - which might be closer to what I figure you might mean:-
Not sure if this makes sense/I'm right at all.
我相信
q->contents[q->size++] = *e;
应该简单地是q->contents[q->size++] = e;
。*
将指针取消引用到内存位置的实际值,我认为您不想要这样——您需要指针。I believe
q->contents[q->size++] = *e;
should simply beq->contents[q->size++] = e;
.The
*
dereferences the pointer to the actual value at the memory location and I don't think you want that--you want the pointer.*e
的类型为QueueElement
,而q->contents[q->size++]
是QueueElement*
>您应该在 e 之前删除
*
或将内容声明为:这取决于您是否尝试存储指针或值。
*e
is of typeQueueElement
andq->contents[q->size++]
is aQueueElement*
You should either drop the
*
before e or declare the contents as:It depends if you are trying to store pointers or values.