Horje
dynamic memory in c Code Example
dynamic memory in c
// 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
best graphic video template for editing free download Code Example best graphic video template for editing free download Code Example
bucket sort Code Example bucket sort Code Example
how to delete data and add from file in c language Code Example how to delete data and add from file in c language Code Example
online c compiler for graphics Code Example online c compiler for graphics Code Example
arduino vscode upload choosing sketch Code Example arduino vscode upload choosing sketch Code Example

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