Research portable Memory game | Исследовать портируемую игру Память
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.1KB

  1. #include "uthash.h"
  2. #include <stdio.h>
  3. #include <stdlib.h> /* malloc */
  4. typedef struct person_t {
  5. char *first_name;
  6. int id;
  7. UT_hash_handle hh;
  8. } person_t;
  9. int main()
  10. {
  11. person_t *people=NULL, *person, *new_person, *tmp;
  12. const char **name;
  13. const char * names[] = { "bob", "jack", "gary", "ty", "bo", "phil", "art",
  14. "gil", "buck", "ted", NULL
  15. };
  16. int id=0;
  17. for(name=names; *name!=NULL; name++) {
  18. person = (person_t*)malloc(sizeof(person_t));
  19. if (person == NULL) {
  20. exit(-1);
  21. }
  22. person->first_name = (char*)malloc(10UL);
  23. if (person->first_name == NULL) {
  24. exit(-1);
  25. }
  26. strcpy(person->first_name, *name);
  27. person->id = id++;
  28. HASH_ADD_STR(people,first_name,person);
  29. printf("added %s (id %d)\n", person->first_name, person->id);
  30. }
  31. person=NULL;
  32. person_t **p=&person;
  33. for(name=names; *name!=NULL; name++) {
  34. HASH_FIND_STR(people,*name,*p);
  35. if (person != NULL) {
  36. printf("found %s (id %d)\n", person->first_name, person->id);
  37. new_person = (person_t*)malloc(sizeof(person_t));
  38. if (new_person == NULL) {
  39. exit(-1);
  40. }
  41. new_person->first_name = (char*)malloc(10UL);
  42. if (new_person->first_name == NULL) {
  43. exit(-1);
  44. }
  45. strcpy(new_person->first_name, person->first_name);
  46. new_person->id = person->id*10;
  47. HASH_REPLACE_STR(people,first_name,new_person,tmp);
  48. printf("replaced (%c) with %s (id %d)\n", (tmp!=NULL)?'y':'n', new_person->first_name, new_person->id);
  49. if (tmp != NULL) {
  50. free(tmp->first_name);
  51. free(tmp);
  52. }
  53. } else {
  54. printf("failed to find %s\n", *name);
  55. }
  56. }
  57. printf("traversing... \n");
  58. HASH_ITER(hh, people, person, tmp) {
  59. printf("%s (id %d)\n", person->first_name, person->id);
  60. HASH_DEL(people,person);
  61. free(person->first_name);
  62. free(person);
  63. }
  64. return 0;
  65. }