0

I need to assign a string (char of size [255]) to an element in a struct. The struct looks like this:

struct node{
   int ID, YEAR, MONTH, DAY
   char CATEGORY[255], DETAIL[255];
   double AMOUNT;
   struct node * next;
}
 struct node * head = NULL;

and I have code that gets values from a text file and sets it as a variable that I then pass to the add_struct function which looks like this:

void add_struct(int i, char c, char d, double a, int y, int m, int da){
   if (head == NULL){
        head = (struct node *) malloc(sizeof(struct node));
        head->ID = i;
        head->CATEGORY = c;
        head->DETAIL = d;
        head->AMOUNT = a;
        head->YEAR = y;
        head->MONTH = m;
        head->DAY = da;
  }

  else {
        struct node * p = head;
        while(p->next != NULL) p = p->next;
        p->next = (struct node *) malloc(sizeof(struct node));
        p->next->ID = i;
        p->next->CATEGORY = c;
        p->next->DETAIL = d;
        p->next->AMOUNT = a;
        p->next->YEAR = y;
        p->next->MONTH = m;
        p->next->DAY = da;
   }
}

I get error message:

"incompatible types when assigning to type 'char[255]' from type 'char'"

How do I assign these values to elements CATEGORY and DETAIL properly?

6
  • char c --> char *c... p->next->CATEGORY = c;--> strcpy(p->next->CATEGORY, c); Commented Apr 30, 2016 at 0:08
  • Does char c, char d, really meant a single char or a pointer to char(string)? Commented Apr 30, 2016 at 0:09
  • Also Need XXX->next = NULL; Commented Apr 30, 2016 at 0:11
  • Also don't cast malloc's return value, just do head = malloc(sizeof(struct node));. Commented Apr 30, 2016 at 0:14
  • @BLUEPIXY thank you this fixed it right up Commented Apr 30, 2016 at 0:16

1 Answer 1

1

The CATEGORY and DETAIL field of the struct are defined as arrays of 255 chars, while c and d are variables of char. So you should change the function to void add_struct(int i, char *c, char *d, double a, int y, int m, int da), and copy the string to the allocated struct:

strcpy(head->CATEGORY, c);
strcpy(head->DETAIL, d);
Sign up to request clarification or add additional context in comments.

2 Comments

the values c and d are not just characters though but char arrays of size 255 as well. an example would be like the CATEGORY being "Restaurant" and the DETAIL being "Waffle House". Does this still work?
@user276019 in that case, you need to fix the function signature, and use strcpy in the function. see my post.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.