Advertisement
Guest User

Create String & Int From Linked List

a guest
Apr 24th, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. // C program for variable length members in
  2. // structures in GCC
  3. #include<string.h>
  4. #include<stdio.h>
  5. #include<stdlib.h>
  6.  
  7. // A structure of type student
  8. struct student
  9. {
  10. int stud_id;
  11. int name_len;
  12.  
  13. // This is used to store size of flexible
  14. // character array stud_name[]
  15. int struct_size;
  16.  
  17. // Flexible Array Member(FAM)
  18. // variable length array must be last
  19. // member of structure
  20. char stud_name[];
  21. };
  22.  
  23. // Memory allocation and initialisation of structure
  24. struct student *createStudent(struct student *s,
  25. int id, char a[])
  26. {
  27. // Allocating memory according to user provided
  28. // array of characters
  29. s =
  30. malloc( sizeof(*s) + sizeof(char) * strlen(a));
  31.  
  32. s->stud_id = id;
  33. s->name_len = strlen(a);
  34. strcpy(s->stud_name, a);
  35.  
  36. // Assigning size according to size of stud_name
  37. // which is a copy of user provided array a[].
  38. s->struct_size =
  39. (sizeof(*s) + sizeof(char) * strlen(s->stud_name));
  40.  
  41. return s;
  42. }
  43.  
  44. // Print student details
  45. void printStudent(struct student *s)
  46. {
  47. printf("Student_id : %d\n"
  48. "Stud_Name : %s\n"
  49. "Name_Length: %d\n"
  50. "Allocated_Struct_size: %d\n\n",
  51. s->stud_id, s->stud_name, s->name_len,
  52. s->struct_size);
  53.  
  54. // Value of Allocated_Struct_size is in bytes here
  55. }
  56.  
  57. // Driver Code
  58. int main()
  59. {
  60. int ID;
  61. char name[99];
  62. printf("Enter ID : ");
  63. scanf("%d", &ID);
  64. printf("Enter Name : ");
  65. scanf("%s", &name);
  66. struct student *s1 = createStudent(s1, ID, name);
  67. printf("Enter ID : ");
  68. scanf("%d", &ID);
  69. printf("Enter Name : ");
  70. scanf("%s", &name);
  71. struct student *s2 = createStudent(s2, ID, name);
  72.  
  73. printStudent(s1);
  74. printStudent(s2);
  75.  
  76. // Size in struct student
  77. printf("Size of Struct student: %lu\n",
  78. sizeof(struct student));
  79.  
  80. // Size in struct pointer
  81. printf("Size of Struct pointer: %lu",
  82. sizeof(s1));
  83.  
  84. return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement