开发者

c programming: need fresh eyes to look at this [demo code != homework]

Essentially I want qPtr[0] to hold sPtr[0]

struct myQueue{  
    struct sample* node;  
    int front;  
    int 开发者_JS百科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;  
}  

I've been at it for about 2 hours now and would appreciate some clarification on what I'm doing wrong conceptually. thank you!


samplePtr[0] gives the object itself, not a pointer to the object. Try sending &samplePtr[0] or samplePtr itself. enque function, second parameter expects a type of struct sample* and not struct sample.


How about:

enqueue(qPtr, &samplePtr[0]);

The second parameter to enqueue() takes a pointer to a struct sample.


Your code has 2 fundamental problems.

  • you're passing a struct sample object to enqueue() instead of a pointer to a struct sample. this should be caught by the compiler.
  • you're setting up an array of queue structures instead of having a single queue structure object that manages an array of pointers to the objects that are on the queue. This is a design problem.

Your code should probably look more like:

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;  
}  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜