Beginner
Beginner

Reputation: 57

expression must be a modifiable lvalue on struct pointer

i'm trying to fill the Item type "temp" with values that are in the array "temp fields" (Contains strings) i get the "expression must be a modifiable lvalue" error on my ptemp pointer.

typedef struct _item {
   char item_name[ITEM_NAME_LENGTH];
   char department[DEPARTMENT_NAME_LENGTH];
   char expiration_date[EXPIRATION_DATE_STRING_LENGTH];
   double price;
   int available;} Item;

Item create_item(char *s) {
    Item temp, *ptemp;
    ptemp = &temp;
    char temp_fields[5];
    int n = 0;
    n = seperate_fields(s, "_*_", temp_fields);
    ptemp->item_name = temp_fields[0];

can anyone explain whay this is happening? im trying to modify the value that the pointer is pointing at. that suppose to be modifiable

i thank anyone who answers in advance

the edited code for item creation

Item create_item(char *s) {
Item temp, *ptemp;
char *ptrend;
char *temp_fields[5];
int n = 0;
ptemp = &temp;
n = seperate_fields(s, "_*_", temp_fields);
strcpy(ptemp->item_name, temp_fields[0]);
strcpy(ptemp->department,temp_fields[1]);
strcpy(ptemp->expiration_date, temp_fields[2]);
ptemp->price = strtod(temp_fields[3], &ptrend);
ptemp->available = atoi(temp_fields[4]);
return temp;

Upvotes: 4

Views: 19225

Answers (1)

John Zwinck
John Zwinck

Reputation: 249133

You're trying to copy a string, but you can't use = for that, because the destination is an array, and you can't just assign arrays in C. Instead of this:

ptemp->item_name = temp_fields[0];

You can do this:

strncpy(ptemp->item_name, temp_fields, ITEM_NAME_LENGTH);
ptemp->item_name[ITEM_NAME_LENGTH - 1] = '\0';

Note I didn't use temp_fields[0] because that would be just one character, which doesn't really make sense. Also note the explicit null termination after strncpy() because that function will not null terminate the output if there isn't enough space.

Upvotes: 7

Related Questions