× Home

Array as an abstract data type in Data structures

ADTs

ADTS → Set of values + Set of operations

An abstract data type is just another data type as an int or float, with some user-defined methods and operations in a heap.

Supporse we want to build an array as an abstract data type with our customized set of values and customized seet of operations in a heap.
Let's name this customized array myArray.
Let our set of values which will represent our customized array include these parameters:

  • total_size
  • used_size
  • base_address

And the operations include operators namely.

  • max()
  • get(i)
  • set(i,num)
  • add(another_array)
So, now when we are done creating a blueprint of the customized array. We can very easily code their implementation, but before that, let's first learn what these values and operations, we have defined, do:

Understanding the ADT above:
  • total_size: This stores the total reserved sized of the array in the memory location.
  • used_size: This stores the size of the memory location used.
  • base_address: This is a pointer that stores the address of the first element of the array.
  • let the below inllustrated array be an example of what we are talking about.
Here, the total_size returns 6, and the used_size returns 3.

#include <stdio.h>
#include <stdlib.h>

struct myArray
{
int total_size;
int used_size;
int *ptr; // point the first element of an array
};

void createArray(struct myArray *a, int tSize, int uSize)
{
// (*a).total_size = tSize;
// (*a).used_size = uSize;
// (*a).ptr = (int *)malloc(tSize * sizeof(int));

// shortcut
a->total_size = tSize;
a->used_size = uSize;
a->ptr = (int *)malloc(tSize * sizeof(int)); // heap memory request
}

void show(struct myArray *a)
{
for (int i = 0; i < a->used_size; i++)
{
printf("%d\n", (a->ptr)[i]);
}
}
void setVal(struct myArray *a)
{
int n;
for (int i = 0; i < a->used_size; i++)
{
printf("Enter Value at marks[%d] :", i);
scanf("%d", &n);
(a->ptr)[i] = n;
}
}

int main()
{
struct myArray marks;
createArray(&marks, 10, 2);
setVal(&marks);
show(&marks);
return 0;
}