Answers for "free allocated memory in c"

C
0

how to free memory in c

int *example = NULL; //create pointer
example = malloc(sizeof(int)); //allocate memory
free(example); //deallocate memory
Posted by: Guest on April-14-2020
1

n no of array in c using malloc

#include <stdio.h>

int main()
{
    printf("nnttStudytonight - Best place to learnnnn");
    int n, i, *ptr, sum = 0;

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

    // dynamic memory allocation using malloc()
    ptr = (int *) malloc(n*sizeof(int));

    if(ptr == NULL) // if empty array
    {
        printf("nnError! Memory not allocatedn");
        return 0;   // end of program
    }

    printf("nnEnter elements of array: nn");
    for(i = 0; i < n; i++)
    {
        // storing elements at contiguous memory locations
        scanf("%d", ptr+i);    
        sum = sum + *(ptr + i);
    }

    // printing the array elements using pointer to the location
    printf("nnThe elements of the array are: ");
    for(i = 0; i < n; i++)
    {
        printf("%d  ",ptr[i]);    // ptr[i] is same as *(ptr + i)
    }

    /* 
        freeing memory of ptr allocated by malloc 
        using the free() method
    */
    free(ptr);

    printf("nntttCoding is Fun !nnn");
    return 0;
}
Posted by: Guest on July-03-2020

Code answers related to "free allocated memory in c"

Code answers related to "C"

Browse Popular Code Answers by Language