Hoşgeldin Misafir

C malloc örnek

MiRaT

13 Kas 2017
2,077 Mesaj

Aktiflik

Seviye

Deneyim

TIM / GÖREV:
-soru:--

-Kullanıcı tarafından girilen n element toplamını bulmak için bir C programı yazın. Bu programı gerçekleştirmek için malloc () işlevini kullanarak bellek dinamik olarak ayırın.--


Kod:
Cevap:

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

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

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

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

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

    printf("Sum = %d", sum);
    free(ptr);
    return 0;
}