Reputation: 2004
I'm simulating inheritance in C, but I'm not so familiar with the language. Below is some of the code. Visual Studio has an error message for emp.name=n
which says:
expression must be a modifiable lvalue.
How do I change it so it can be modified?
typedef struct {
char name[20];
double salary;
} Employee;
Employee newEmployee(char n[], double s)
{
Employee emp;
emp.name=n;
emp.salary=s;
return emp;
}
Upvotes: 1
Views: 2544
Reputation:
You need to copy the data from n
to Employee.name
:
strncpy(emp.name, n, 20);
However, if n
is not NULL-terminated, you will run into problems. Use the following code to guarantee that emp.name
will be a NULL-terminated string:
strncpy(emp.name, n, 19);
emp.name[19] = '\0';
Upvotes: 5
Reputation: 8162
The other posters are correct to steer you towards using strncpy.
The comments around strcpy vs strncpy arise because strcpy requires that its src character buffer is null terminated, ie. the last character has to be a '\0' character. Failure to follow this convention results in the program terminating unexpectedly with a segmentation fault. It's just embarrassing when that happens.
The error message that you received was pointing out that by attempting to assign the char[] to emp.name you were attempting to modify the address of the name element in your struct. It is not possible to modify the addresses of memory; so the exact the answer to you question is that emp.name will never be modifiable because it is an address in memory and you cannot change that.
So in your head you are thinking I want to modify emp.name to be the data in the the char array n, but the address of emp.name is unmodifiable. strncpy will copy the data contained in the char array n to the 20 bytes that the emp.name address points to.
I may not have explained this very well, do ask more questions. Other posters can correct or refine this answer.
This is the tricky part of learning C; it is useful to study some assembly language and to bear in mind that when you are coding in C you are a thin layer of C language keywords above writing assembler, which is why it's lightning fast and error prone fun.
Upvotes: 1
Reputation: 754280
You have to use strcpy()
or a relative (strncpy()
, memmove()
, memcpy()
, ...) to copy strings in C.
strcpy(emp.name, n);
This assumes that the length of the string in n
is shorter than the name
in the Employee structure. If it isn't, you've got problems.
Upvotes: 1