gcc pointer error did you mean to use ‘->’? [closed]

泪湿孤枕 提交于 2021-02-08 11:53:22

问题


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;

And I have this code

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

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

c206.c: In function ‘DLInsertFirst’: c206.c:104:8: error: ‘*newPtr’ is a pointer; did you mean to use ‘->’? newPtr->lptr = NULL;

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


回答1:


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!!

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).




回答2:


I suspect your first data struct should look like this:

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

This should make it clearer what's going on.



来源:https://stackoverflow.com/questions/46873234/gcc-pointer-error-did-you-mean-to-use

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!