0
Q:

c malloc array

// Use malloc to allocate memory
ptr = (castType*) malloc(size);
int *exampl = (int*) malloc(sizeof(int));
// Use calloc to allocate and inizialize n contiguous blocks of memory
ptr = (castType*) calloc(n, size);
char *exampl = (char*) calloc(20, sizeof(char));
3
//malloc or "memory allocation" reserves a part of the memory

pointer = (cast-type*) malloc(byte-size)
  
//Example
ptr = (int*) malloc(100 * sizeof(int));

Since the size of int is 4 bytes, this statement will allocate 400 bytes
of memory. And, the pointer ptr holds the address of the first byte in
the allocated memory.
4
ptr = (cast-type*)calloc(n, element-size);
3
#include <stdlib.h>

void *malloc(size_t size);

void exemple(void)
{
  char *string;
  
  string = malloc(sizeof(char) * 5);
  string[0] = 'H';
  string[1] = 'e';
  string[2] = 'y';
  string[3] = '!';
  string[4] = '\0';
  printf("%s\n", string);
}

/// output : "Hey!"
2

// 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++;
}
0
#define ARR_LENGTH 2097152
int *arr = malloc (ARR_LENGTH * sizeof *arr);
0
ptr = (cast-type*) malloc(byte-size)
0

New to Communities?

Join the community