0

Ok I am creating an ADT for a singly linked list. I have a Struct name List that stores the pointer to the first node(first item in the list, which is also a struct)and size. The node stores first name and a pointer to the next node. Here are the sturcts:

typedef struct List *ListP;

struct List{
   ListP head;
   int size;
   };

struct node{
   char name[20];
   nodeP next;
   };

First I called malloc to give me memory for struct List:

ListP newList;
    newList = malloc(sizeof(struct List)); //should I typecast this to (ListP *)?
    if (newList == NULL){
         fprintf(stderr, "Memory allocation failed");
    }
    else{
        newList->head = NULL;    
        newList->size = 0;       
    }

Then I called malloc again to give me memory for the first node:

struct node *new;
    newNode = malloc(sizeof(struct node));
    if (newNode == NULL){
         fprintf(stderr, "Memory allocation failed");
    }
    else{
        newNode->name = 'Jay';
        newNode->next = NULL;  

Now that I have my List and a new node, I assigned list->head to the address of the new node;

newList->head = newNode;

Untill this time the compiler doesn't complain. But when I try to access the elements in the first node using the pointer that I have for the list:

name = newList->head->name;

The compiler complains that struct List has no member named 'name'

How can I access the field in struct node, assuming that I only have pointer to the struct List and List->head is pointing to the first node. Any help would be appreciated.

2

1 Answer 1

2

You declared head as a ListP when it should be of type NodeP assuming that NodeP is a node*.

Try being consistent with names. Here is a suggested revision:

// forward declarations
struct List;
struct Node;

typedef struct List *ListP;
typedef struct Node *NodeP;

struct Node{
   char name[20];
   NodeP next;
};

struct List{
   NodeP head;
   int size;
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.