Search
 
SCRIPT & CODE EXAMPLE
 

C

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;
}
Comment

dynamic memory allocation c

#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
    printf("Enter number of elements:");
    scanf("%d",&n);
    printf("Entered number of elements: %d
", n);
 
    // Dynamically allocate memory using malloc()
    ptr = (int*)malloc(n * sizeof(int));
 
    // Check if the memory has been successfully
    // allocated by malloc or not
    if (ptr == NULL) {
        printf("Memory not allocated.
");
        exit(0);
    }
    else {
 
        // Memory has been successfully allocated
        printf("Memory successfully allocated using malloc.
");
 
        // 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;
}
Comment

PREVIOUS NEXT
Code Example
C :: how to scanf two dimensional array in c 
C :: c pass int by reference 
C :: Access denied creating xampp-control.ini 
C :: convert int to string c 
C :: implicit declaration of function ‘usleep’ [-Wimplicit-function-declaration] 
C :: append to list in c 
C :: Firebase Connecting with ESP8266 
C :: c radians 
C :: how to get input in 2d array in c 
C :: convert int to char in c 
C :: mpi example 
C :: c programming language 
C :: c round float 
C :: keep last n bits 
C :: int to double c 
C :: do...while loop c 
C :: bubble sort c 
C :: calculate median 
C :: sockaddr_in c 
C :: leggere stringhe con spazio in mezzo c 
C :: wifi access point in esp8266 
C :: vifm preview images 
C :: c malloc array 
C :: declare and initialize a string in C 
C :: C How to define a union? 
C :: allintext:christie kiser filetype:log 
C :: Syntax for creating a node 
C :: main prototype 
C :: hgggggggggggggggg 
C :: remove every appearance of char without malloc in c 
ADD CONTENT
Topic
Content
Source link
Name
8+1 =