0

I made a linked list whose nodes hold 4 string values. When I call the newNode function, an error says 'Node has no member named familyName', as well as the other members. My code:

I am really confused with how strings work in structs.

user3195991
  • 79
  • 1
  • 1
  • 7

2 Answers2

1

Your immediate problem is the type definition. You cannot call malloc() from within there, all you can do is define the fields. The memory allocation must come later. So, it should be:

typedef struct node{
    char *familyName;
    char *firstName;
    char *address;
    char *phoneNumber;
    struct node *link;
}Node;

You'll strike another problem (run-time rather than compile-time) once you fix that. When you do something like:

p -> familyName = famName;

that simply copies the pointer into your structure, and the pointer is always the memory location of familyName in main().

That means every node will point to the same memory, and you're continuously updating that memory.

You won't notice the problem with the code as it stands, since you're only asking for one record. But it will become an issue when you start looping to get more records.

Your best bet is to use something like strdup() to make a copy of the string passed in, then each node will have its own memory location for strings:

p -> familyName = strdup (famName);

(don't forget to also free() the memory for each field once you're finished with it).

In the unlikely event your C implementation doesn't have a strdup(), see here.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

There are several problems:-

  • It is not allowed to allocate memory when declaring a structure. Either, do the malloc inside your newNode() method Or, declare the structure like char familyName[50].
  • Result of malloc should not be casted.
  • It is better to use strcpy (or strdup) when copying strings
Siddhartha Ghosh
  • 2,988
  • 5
  • 18
  • 25