Vipasana Vipasana - 5 months ago 35
C Question

Structs fields assignment in C

I have a MyLinkedList.h file with this lines:

typedef struct _MyLinkedList *MyLinkedListP;

And in my .c file, I try this and it won't work.

#include "MyLinkedList.h"

typedef struct _Node
int _val;
struct _Node* next;
} Node;

typedef struct _MyLinkedList
int _listSize;
Node* _firstNode;

MyLinkedListP createList()
MyLinkedListP *list = (MyLinkedListP*)malloc(sizeof(MyLinkedListP));
list._listSize = 0;
list._firstNode = NULL;

The ._listSize and ._firstNode is red colored.
What am I doing wrong?


You have two errors:

  • MyLinkedListP is already a pointer, so MyLinkedListP *list is a pointer to a pointer.
  • You use ->, not ., to access struct fields from a pointer.

Here is how to fix your code:

MyLinkedListP list = malloc(sizeof(struct _MyLinkedList));
//           ^       ^
//  No asterisk      No cast          
list->_listSize = 0;
list->_firstNode = NULL;