Home C-tutorials C Dynamic Array



C Dynamic Array
Posted on: February 5, 2009 at 12:00 AM
The dynamic array is an array data structure which can be resized during runtime which means elements can be added and removed.

C Dynamic Array

     

In this section, you will learn how to determine the size of a dynamic array in C.

The dynamic array is an array data structure which can be resized during runtime which means elements can be added and removed.  You can see in the given example that we prompt the user to enter the number of elements that he want to set into the array.

The expression (int*)malloc(n*sizeof (int)) stores the number of elements in the memory. The malloc is basically used for memory allocation. By using the for loop the variable i reads the elements from the memory and displays the required array.

Here is the code:

 

 

DYNAMICA.C

 

 

 

#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main() {
  int* array;
  int n, i;
  printf("Enter the number of elements: ");
  scanf("%d", &n);
  array = (int*) malloc(n*sizeof(int));
  for (i=0; i<n; i++) {
  printf("Enter number %d: ", i);
  scanf("%d", &array[i]);
  }
  printf("\nThe Dynamic Array is: \n");
  for (i=0; i<n; i++) {
  printf("The value of %d is %d\n", i, array[i]);
  }
  printf("Size= %d\n", i);
  getch();
  return 0;
}

Output will be displayed as:

DYNAMICA.EXE

Download Source Code:

Related Tags for C Dynamic Array:
carrayantdynamicdatatimestructruntimeresizesizeuserremovestructureurinumberintsetelementmoveelementspromptexampleaddtoexamrunecanuseimenterddeinamimnttrwancaddadesemmemeanintoproxawhichxampseeataddedishaimeivmplrayeaduandarstrwantzruntsruntsriringthsthatesiesipleplprmovmindomo


More Tutorials from this section

Ask Questions?    Discuss: C Dynamic Array   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.