Suppose you have the following C struct:
1. typedef struct
2. {
3. char* name;
4. }Emp;
I asked in
SO on how to determine the amount of memory to allocate to the char* struct member. and the answer was to use lazy/delayed allocation as of:
1. void setName(Emp* emp, char* newName)
2. {
3. free(emp->name);
4. emp->name = malloc(strlen(newName) + 1);
5. strcpy(emp->name, newName);
6. }
(It seems to me to be the same idea used for Objective-C, the setter is release the previous pointer and then retain (in C to copy) the parameter pointer.
So, the whole program will be:
1. #include <stdio.h>
2. #include <string.h>
3. #include <stdlib.h>
4.
5. typedef struct
6. {
7. char* name;
8. }Emp;
9.
10. void init(Emp** emp)
11. {
12. *emp = malloc(sizeof(Emp));
13. (*emp)->name = NULL;
14. (*emp)->name = malloc(sizeof(char*));
15. }
16.
17. void release(Emp** emp)
18. {
19. free((*emp)->name);
20. free(*emp);
21. }
22.
23. void setName(Emp* emp, char* newName)
24. {
25. free(emp->name);
26. emp->name = malloc(strlen(newName) + 1);
27. strcpy(emp->name, newName);
28. }
29. char* getName(Emp* emp)
30. {
31. return emp->name;
32. }
33.
34. int main(void)
35. {
36. Emp* emp;
37. init(&emp);
38. setName(emp, "Muhammad Abdullah");
39. printf("%s", getName(emp));
40. release(&emp);
41.
42. return 0;
43. }
No comments:
Post a Comment