Tuesday, 22 August 2023

Dynamic Memory Allocation. DMA functions malloc(), calloc(), free() etc.

Malloc and Calloc in C

Malloc and Calloc in C

#include stdio.h
#include stdlib.h

int main()
{
  int *mry;
  int *mry2;
  int n;

  printf("ENTER SIZE OF ARRAY::");
  scanf("%d", &n);

  mry = (int *)malloc(n * sizeof(int));
  mry2 = (int *)calloc(n, sizeof(int));

  if (mry == NULL)
    printf("MEMORY NOT ALLOCATED::");
  else
  {
    printf("MALLOC FUNCTION::\n");
    printf("ENTER ARRAY ELEMENT::");
    for (int i = 0; i < n; i++)
    {
      scanf("%d", &mry[i]);
    }
    for (int i = 0; i < n; i++)
    {
      printf("%d, ", mry[i]);
    }
  }

  free(mry);

  if (mry2 == NULL)
    printf("\nMemory Not allocated");
  else
  {
    printf("\nCALLOC FUNCTION::\n");
    int sum = 0;
    printf("ENTER ARRAY ELEMENT::");
    for (int i = 0; i < n; i++)
    {
      scanf("%d", &mry2[i]);
      sum = sum + mry2[i];
    }
    printf("Sum of Array is %d", sum);
    free(mry2);
  }

  return 0;
}

1 comment:


  1. Output:

    ENTER SIZE OF ARRAY::3

    MALLOC FUNCTION::

    ENTER ARRAY ELEMENT::1 2 3

    1, 2, 3,

    CALLOC FUNCTION::

    ENTER ARRAY ELEMENT::4 5 1

    Sum of Array is 10

    ReplyDelete

Interactive Report: Introduction to the Internet of Things (IoT) ...

Popular Posts