c - C 的新手 : Storing Structures in an Array

标签 c arrays structure

我的第一个 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 */

        }
}

非常感谢对这个问题的任何帮助以及任何其他建议。 谢谢大家。

最佳答案

我相信你的意思

q->contents[q->size++] = e;

(没有星号) 因为您要将 QueueElement* 类型的内容分配给 QueueElement*[] 数组。

或者您可以通过更改它来修复它 - 这可能更接近我认为您的意思:-

QueueElement contents[QUEUE_SIZE];

不确定这是否有意义/我完全正确。

关于c - C 的新手 : Storing Structures in an Array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4824374/

相关文章:

php - 使用 php 进行数组搜索

C - 当尝试更新记录时,fseek() 会影响文件的内容(结构)

c - 将结构传递给 C 中的函数

c - 为什么我会收到不兼容的指针类型错误?

arrays - 推断元组数组中的类型

c - 更新到 GLIBC_2.29 时缺少 libcap.so.2

c - 通过引用传递 int/char 数组的错误/警告

c - 整理代码 - 将辅助函数隐藏在不同的文件中

当程序在不同的地方遇到错误并退出时,C 如何释放 malloc 的内存?

c - 增加在数组指针数组中实现的数组的最后一行?