Saturday, December 15, 2018

Structure, Union and Memory Allocation

Structure is a collection of various types of data in which can contain a variable or array, structure capacity is the sum of all variables and arrays defined.


Union is the same thing as the structure starting from the application, assign it, and also the declarations, the difference is that Union only uses the capacity of the largest variable of the union.


Memory Allocation is a function that takes memory from RAM to be used in the program.
Memory De-Allocation is a function to restore memory from a program back to RAM.
There are two basic types of memory allocation: When you declare a variable or an instance of a structure or class.

Example of structure:
# include
# include

struct mhs {
  char nim[9];
  char name[26];
  float gpa;
};
Use of structure:
int main (){
  struct mhs lia;
  float wgpa;

  scanf("%s", &lia.nim);
  fflush(stdin);
  gets(lia.name);
  scanf("%f", &wgpa);
  lia.gpa = wgpa;
  printf("%s %s %.2f",
  lia.nim, lia.name, lia.gpa);
  return 1;
}
Example of union:
union  name_union{
     typedata1  name_var1 ;
     typedata2   name_var2;
     ……
} name_var_union;

union  name_union   name_var_union;  

Enumeration is the naming of a variable or a struct.

Example of memory allocation:
# include
# include
int main() {
  int *arr, n, i;
  do { 
    fflush(stdin);
    printf(“total element ? ");
    scanf("%d", &n);
    if (n == 0) break;
    arr = (int *) malloc (n * sizeof(int));
    printf(“Input %d numbers: ", n);
    for (i = 0; i < n; i++) scanf(“%d", &arr[i]);
    printf(“reversed: ");
    for (i = n - 1; i >= 0; i--) printf("%d ", arr[i]);
    printf("\n\n");
    free(arr);
  }while (1);
  return 1;

By :Steven
2201852132

Computer Science and Statistics

No comments:

Post a Comment