how to malloc an array in c code example

Example 1: malloc int array c

int array_length = 100;
int *array = (int*) malloc(array_length * sizeof(int));

Example 2: c allocate array

int *array = malloc(10 * sizeof(int));

Example 3: how to dynamically allocate array size in c

// declare a pointer variable to point to allocated heap space
int    *p_array;
double *d_array;

// call malloc to allocate that appropriate number of bytes for the array

p_array = (int *)malloc(sizeof(int)*50);      // allocate 50 ints
d_array = (int *)malloc(sizeof(double)*100);  // allocate 100 doubles


// use [] notation to access array buckets 
// (THIS IS THE PREFERED WAY TO DO IT)
for(i=0; i < 50; i++) {
  p_array[i] = 0;
}

// you can use pointer arithmetic (but in general don't)
double *dptr = d_array;    // the value of d_array is equivalent to &(d_array[0])
for(i=0; i < 50; i++) {
  *dptr = 0;
  dptr++;
}

Example 4: c malloc array

#define ARR_LENGTH 2097152
int *arr = malloc (ARR_LENGTH * sizeof *arr);

Example 5: how to use malloc in c

int* a =(int*)malloc(sizeof(int))

Example 6: what is the use of malloc in c

In C, the library function malloc is used to allocate a block of memory on the heap. The program accesses this block of memory via a pointer that malloc returns. When the memory is no longer needed, the pointer is passed to free which deallocates the memory so that it can be used for other purposes.

Tags:

C Example