Q:

dynamic memory allocation in c

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
#include <stdio.h> 
#include <stdlib.h> 
  
int main() 
{ 
  
    // This pointer will hold the 
    // base address of the block created 
    int* ptr; 
    int n, i; 
  
    // Get the number of elements for the array 
    n = 5; 
    printf("Enter number of elements: %d\n", n); 
  
    // Dynamically allocate memory using calloc() 
    ptr = (int*)calloc(n, sizeof(int)); 
  
    // Check if the memory has been successfully 
    // allocated by calloc or not 
    if (ptr == NULL) { 
        printf("Memory not allocated.\n"); 
        exit(0); 
    } 
    else { 
  
        // Memory has been successfully allocated 
        printf("Memory successfully allocated using calloc.\n"); 
  
        // Get the elements of the array 
        for (i = 0; i < n; ++i) { 
            ptr[i] = i + 1; 
        } 
  
        // Print the elements of the array 
        printf("The elements of the array are: "); 
        for (i = 0; i < n; ++i) { 
            printf("%d, ", ptr[i]); 
        } 
    } 
  
    return 0; 
} 
2
ptr = (castType*)calloc(n, size);
1

New to Communities?

Join the community