C - Write program to allocate space for three int values array

Requirements

Write a program that allocates space for three int values array by using one malloc() function.

Assign 100, 200, and 300 to each int, and then display all three values.

Hint

The size of three integer can be calculated as

sizeof(int)*3

Demo

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

int main()//from   ww  w . j  ava  2  s . co m
{
    int *three;
    int x;

    three = (int *)malloc(sizeof(int)*3);
    if(three == NULL)
    {
        puts("Unable to allocate memory");
        exit(1);
    }

    *three = 100;
    *(three+1) = 200;
    *(three+2) = 300;

    for(x=0;x<3;x++)
        printf("%d: %d\n",x+1,*(three+x));

    return(0);
}

Result

Related Exercise