基本上我想要qPtr [0]来保存sPtr [0]
struct myQueue{
struct sample* node;
int front;
int size;
int numElements;
};
struct sample{
int field1[5];
char field2[10];
}
int main(){
struct myQueue* qPtr = malloc(10 * sizeof(struct myQueue);
struct sample* samplePtr = malloc(10 * sizeof(struct sample); //assume this array has been initialized
enqueue(qPtr, samplePtr[0]); //this does not work
}
//returns 1 if enqueue was successful
int enqueue(struct myQueue* qPtr, struct sample* sPtr){
qPtr->node[(qPtr->front + qPtr->numElements) % qPtr->size] = sPtr; //code pertains to circular array implementation of queues
return 1;
}
我现在已经在这里待了大约2个小时,并希望在概念上澄清我做错了什么。谢谢!
答案 0 :(得分:1)
samplePtr[0]
给出了对象本身,而不是指向对象的指针。尝试发送&samplePtr[0]
或samplePtr
本身。 enque
函数,第二个参数需要struct sample*
而不是struct sample
。
答案 1 :(得分:0)
怎么样:
enqueue(qPtr, &samplePtr[0]);
enqueue()的第二个参数采用指向struct sample的指针。
答案 2 :(得分:0)
您的代码有两个基本问题。
struct sample
对象传递给enqueue()
,而不是指向struct sample
的指针。这应该被编译器捕获。您的代码可能看起来更像:
struct myQueue{
struct sample* node;
int front;
int size;
int numElements;
};
struct sample{
int field1[5];
char field2[10];
}
struct myQueue q = {0};
int enqueue(struct myQueue* qPtr, struct sample* sPtr);
int main(){
// get memory to hold a collection of pointers to struct sample:
q.node = calloc(10, sizeof(struct sample*));
q.size = 10;
// allocate a sample
struct sample* samplePtr = malloc(sizeof(*samplePtr));
// put the sample on the queue
enqueue(qPtr, samplePtr);
}
//returns 1 if enqueue was successful
int enqueue(struct myQueue* qPtr, struct sample* sPtr){
qPtr->node[(qPtr->front + qPtr->numElements) % qPtr->size] = sPtr; //code pertains to circular array implementation of queues
return 1;
}