Answers for "c length of malloc array"

C
7

array length c

int prices[5] = { 1, 2, 3, 4, 5 };

int size = sizeof prices / sizeof prices[0];

printf("%u", size); /* 5 */
Posted by: Guest on June-16-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 "C"

Browse Popular Code Answers by Language