【问题标题】:c programming: need fresh eyes to look at this [demo code != homework]c 编程:需要新鲜的眼睛来看看这个[演示代码!=作业]
【发布时间】:2011-03-12 07:03:23
【问题描述】:

基本上我希望 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 个小时,希望能澄清一下我在概念上做错了什么。谢谢!

【问题讨论】:

    标签: c pointers data-structures struct


    【解决方案1】:

    samplePtr[0] 给出对象本身,而不是指向对象的指针。尝试发送 &samplePtr[0]samplePtr 本身。 enque 函数,第二个参数需要 struct sample* 类型而不是 struct sample

    【讨论】:

    • @jeeper_creepers - 你的评论“假设这个数组已经被初始化”,我假设myQueue 的结构成员也是初始化的有效值。你是这个意思吗?
    【解决方案2】:

    怎么样:

    enqueue(qPtr, &samplePtr[0]);
    

    enqueue() 的第二个参数接受一个指向结构样本的指针。

    【讨论】:

      【解决方案3】:

      您的代码有 2 个基本问题。

      • 您将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;  
      }  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-30
        • 1970-01-01
        • 2014-08-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多