Horje
malloc basics Code Example
malloc basics
// Program to calculate the sum of n numbers entered by the user

#include <stdio.h>
#include <stdlib.h>

int main() {
  int n, i, *ptr, sum = 0;

  printf("Enter number of elements: ");
  scanf("%d", &n);

  ptr = (int*) malloc(n * sizeof(int));
 
  // if memory cannot be allocated
  if(ptr == NULL) {
    printf("Error! memory not allocated.");
    exit(0);
  }

  printf("Enter elements: ");
  for(i = 0; i < n; ++i) {
    scanf("%d", ptr + i);
    sum += *(ptr + i);
  }

  printf("Sum = %d", sum);
  
  // deallocating the memory
  free(ptr);

  return 0;
}




C

Related
recursion function bangla Code Example recursion function bangla Code Example
no module names skimage Code Example no module names skimage Code Example
how to merge 2 bytes into an integer Code Example how to merge 2 bytes into an integer Code Example
c read file from command line Code Example c read file from command line Code Example
UTC offset upper limit Code Example UTC offset upper limit Code Example

Type:
Code Example
Category:
Coding
Sub Category:
Code Example
Uploaded by:
Admin
Views:
14