top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Creating a Dynamic array ADT in C?

+2 votes
724 views

I am having trouble with the creating a dynArray and adding elements to it. I am not sure how to allocate memory for it. I have only recently started pointers so any help would be much appreciated.

typedef struct{
  doube *darray;
  int size;
} dynArray;

dynArray *createDynArray(int n);
{
  dynArray *newdynArray;  //newdynArray is a pointer to the dynArray structure
  newDynArray->darray=(double*)malloc(n*double);
}
posted Mar 13, 2016 by Shivam Kumar Pandey

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

3 Answers

+1 vote

You need to allocate space for both the container and the array itself:

typedef struct dynArray {
  double *darray;
  int size;
} dynArray;

dynArray *createDynArray(int n) {
    dynArray *newDynArray = malloc(sizeof(dynArray));
    newDynArray->size = n;
    newDynArray->darray = calloc(n, sizeof(double));
    return newDynArray;
}

void deleteDynArray(dynArray *dynArray) {
    free(dynArray->darray);
    free(dynArray);
}
answer Mar 14, 2016 by Manikandan J
+1 vote

You have newDynArray which points to the dynamic array for which also you need to allocate memory -

Try something like this (Not tested)

dynArray *createDynArray(int n) {
    dynArray *newDynArray = malloc(sizeof(dynArray));
    newDynArray->size = n;
    newDynArray->darray = calloc(n, sizeof(double));
    return newDynArray;
}

Remember to free both in your free operation to avoid the memory leak.

answer Mar 14, 2016 by Salil Agrawal
0 votes

typedef struct{
double *darray;
int size;
} dynArray;

dynArray *createDynArray(int n);
{

         dynArray *newdynArray=NULL;     //newdynArray is a pointer to the dynArray structure
           newdynArray=(dynArray *)malloc(sizeof(dynArray);   // this will allocate the memory for the structure..

     // now to allocate memory dynamically for the array darray for n double type elements

       newdynArray->darray=(double *)malloc(sizeof(double)*n);
        return newdynArray;   // returning pointer to structure type

}

answer Mar 29, 2016 by Aman Mehrotra
...