本文介绍了gcc指针错误是您要使用'->'吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在头文件中定义了结构

I have defined structs in header file

typedef struct tDLElem {                 
        int data;                 
        struct tDLElem *lptr;     
        struct tDLElem *rptr; 
} *tDLElemPtr;

typedef struct { 
    tDLElemPtr First;
    tDLElemPtr Act; 
    tDLElemPtr Last;
} tDLList;

我有这个代码

void DLInsertFirst (tDLList *L, int val) {
    tDLElemPtr *newPtr = (tDLElemPtr *) malloc(sizeof(struct tDLElem));
    if (newPtr == NULL)
        DLError();
    newPtr->lptr = NULL;
    newPtr->rptr = L->First;
    newPtr->data = val;
    if (L->First != NULL)
    {
        L->First->lptr = newPtr;
    }
    else
    {
        L->Last = newPtr;
    }
    L->First = newPtr;
}

对我来说似乎很好,但是当我尝试构建它时,gcc说

It seems fine to me but when I try to build it, gcc says

c206.c:109:18:警告:来自不兼容指针类型的分配[-Wincompatible-pointer-types] L-> First-> lptr = newPtr;

c206.c:109:18: warning: assignment from incompatible pointer type [-Wincompatible-pointer-types] L->First->lptr = newPtr;

您能告诉我我的代码在哪里错误吗?而且主要是为什么它在我在那里使用时告诉我使用'->'?谢谢

Can you tell me where is my code wrong ? And mostly why is it telling me to use '->' when I use it there ? Thanks

推荐答案

如注释中所述,您没有使用指针正确地构造.

As mentioned in comments, you are not using your pointer to struct correctly.

typedef struct tDLElem {                 
        int data;                 
        struct tDLElem *lptr;     
        struct tDLElem *rptr; 
} *tDLElemPtr; // note that tDLElemPtr is a pointer!!

将此typedeftDLElemPtr一起使用意味着您将声明的变量为struct tDLElem *( pointer !!! ),因此tDLElemPtr *newPtr是指向指针的指针(struct tDLElem ** ),实际上是newPtr->lptr = NULL;应该是(*newPtr)->lptr = NULL;(我在这里添加了另一个间接访问结构本身的方法).

Using this typedef with tDLElemPtr means the variable you will declare is a struct tDLElem * (pointer!!!), thus tDLElemPtr *newPtr is a pointer to pointer (struct tDLElem **), meaning newPtr->lptr = NULL; should actually be (*newPtr)->lptr = NULL; (I added here another indirection to access the struct itself).

这篇关于gcc指针错误是您要使用'->'吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 11:01