1

使用链表从链表的头部提取数据。数据已经在 Head 中设置,但是当我尝试访问它时,我得到了那个错误。认为指针有问题,但我无法解决。

int main(int argc, char **argv)
{
    int i;

    struct timeval start, end;
    struct element *Head = NULL;
    struct element *Tail = NULL;

    //creating job queue
    for (i = 0; i < NUMBER_OF_JOBS; i++) {
        addLast(generateProcess(), &Head, &Tail);
    }

    //go through job queue running processes and removing processes
    while (Head) {
        runPreemptiveJob(Head->pData, &start, &end);

        int responseTime = getDifferenceInMilliSeconds(Head->pData->oTimeCreated, start);

        printf("Response Time is: %d\n", responseTime);

        Head = Head->pNext;
    }
}

我希望能够通过 head 元素访问 oTimeCreated 中的数据,该元素在其数据字段中具有结构。

错误是在调用 getDifferenceInMilliSeconds 函数时:我在 Head 上收到一个错误,上面写着“表达式必须具有指向结构或联合类型的指针。

元素显示在这里:

struct element
{
    void * pData;
    struct element * pNext;
};

generateProcess() 返回一个结构体过程,定义如下:

struct process
{
    int iProcessId;
    struct timeval oTimeCreated;
    struct timeval oMostRecentTime; 
    int iInitialBurstTime;
    int iPreviousBurstTime;
    int iRemainingBurstTime;
    int iPriority;
};

在主函数中,generateProcess() 返回一个指向进程的指针。该指针被放入链接列表中,因此我试图访问 oTimeCreated 变量,该变量是该结构的一部分,该结构是列表的头部。

4

1 回答 1

0

错误不是关于Head,而是关于Head->pData。请密切注意错误消息。对于某些编译器,错误消息清楚地标识了一行,但不是该行中的确切位置;如果您的编译器的错误不清楚,您可以通过添加换行符并创建更多中间变量来获得更精确的错误位置。

void *data = Head->pData;
struct timeval time_created = data->oTimeCreated;
int responseTime = getDifferenceInMilliSeconds(time_created, start);

请注意,要以这种方式编写代码,我必须为中间表达式Head->pDatadata->oTimeCreated. 为了弄清楚要给出什么类型,我查看了struct element和的定义struct process

特别是 的类型Head->pDatavoid*。那是指向未指定类型的指针。您不能取消引用它,特别是data->oTimeCreated会导致编译错误,因为data它不是指向结构或联合的指针。未指定的类型不是结构或联合。

C 语言中没有多态性。它允许通过 void 指针实现多态性,但就像 C 中的许多事情一样,您需要自己完成一些工作。如果您只有一个指向它的 void 指针,C 不会跟踪对象的实际类型。您必须指定何时要取消引用指针,并且需要正确处理,否则任何事情都可能发生

如果您确定放入列表中的是指向struct process仍然有效的 a 的指针,则将 void 指针转换或强制转换为指向 a 的指针struct process。这是一种惯用的方法:

struct process *head_process = Head->pData;
runPreemptiveJob(head_process, &start, &end);
int responseTime = getDifferenceInMilliSeconds(head_process->oTimeCreated, start);
于 2019-10-17T22:23:34.250 回答