Situation:
A struture pointer consisting of 3 character arrays + 1 int is populated with values via strcpy() and a 'normal' assignment.
The 'problem':
I am confused why assigning a list to the dynamically declared structure pointer does not work.
The following resources show 'how' a list of values are assigned to a structure pointer using the strcpy() function so I know 'how' to do so.
But because I'm still learning C I don't understand 'why' this is the way it's done. I'm hoping someone can point it out to me. Google searching hasn't helped much because I'm really not sure what to look for.
- The C Programming Language, Second Edition (TCPL) [pg 143, lines 5-7]
- Thinking in C - Beta 3 (TIC) [Ch7 - Solution]
- C By Example - Academic Edition (CBE) [pg 523]
- C For Dummies - Volume 2 (CFD) [pg 904-905]
NOTE:
The attached files are from the Chapter 7 Exercise - Solution. The license for the TIC material (presentation, source code).
This seminar is licensed under the Creative Commons "Attribution-NonCommercial-NoDerivs 2.5" license, which means that you may freely distribute the entire package as long as you give attribution to the authors, but you may not sell it or modify it. See the link above for more detail.
The following sources show the strcpy() function being used to copy values into the members of a structure pointer instead of assigning a list.
In employ2.c the following is found:
Code:
struct Employee* createEmployee(char* last, char* first, char* title, int salary)
{
struct Employee* p = malloc(sizeof(struct Employee));
if (p != NULL)
{
strcpy(p->last, last);
strcpy(p->first, first);
strcpy(p->title, title);
p->salary = salary;
}
return p;
}
That is a working function from the solution copy of employ2.c
When the exercise was presented the files you were given were employ2.h and lab7.c. The user was given the task of fleshing out an employ2.c file of their own.
So far I'm not doing too well:
Code:
/* Allocate an Employee struct on the heap and initialize it with
it's arguments, then return the pointer returned from malloc() */
struct Employee* createEmployee(char *last, char *first, char *title, int salary) {
struct Employee *emp =
(struct Employee *)malloc(sizeof(struct Employee));
*emp = { last, first, title, salary };
return emp;
}
Even though the solution did not typecast the void pointer from malloc I did so because of the reference material I was using. All of them predate C99 with TCPL SE being the oldest.
I have a feeling this is blatantly obvious but I'm not 'getting' it.
Thanks in advance for your help.